Python:获取对之间的距离
在我们的数据集中,我们有一大组序列,例如“aismeorisityou”,我们希望得到两个相邻对之间的距离。在这个例子中,在这两个“是”之间还有6个字母。最好的办法是什么 这就是我们所能做到的Python:获取对之间的距离,python,Python,在我们的数据集中,我们有一大组序列,例如“aismeorisityou”,我们希望得到两个相邻对之间的距离。在这个例子中,在这两个“是”之间还有6个字母。最好的办法是什么 这就是我们所能做到的 count = 0 for i in range(1, len(x)): if x[i] == x[i-1]: # True if there are pairs - now count the distance return None 输出应为距离6 您需要第二个内循环: x=
count = 0
for i in range(1, len(x)):
if x[i] == x[i-1]:
# True if there are pairs - now count the distance
return None
输出应为距离6 您需要第二个内循环:
x= 'aismeorisityou'
for i in range(1, len(x)):
for j in range(i+1, len(x)-1):
if x[i] == x[j] and x[i+1]==x[j+1]:
print(x[i]+x[i+1])
print('separated by: ' + str(j-i))
返回:
is
separated by: 6
我希望有帮助 如果序列是字符串,例如:“aismeorisityou” 您可以使用字符串查找(或索引)子字符串“is”,然后返回这两个字符串
>>> s.index('is')
1
>>> s.rindex('is')
7
>>> s.find('is')
1
>>> s.rfind('is')
7
>>>
写入def,然后返回之间的空格
但是,您可以从文档中找到:
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
输入字符串的完整输出是什么?为什么这两个
isit
s之间的距离不是?或i
s`等etc@Dan输出应该是距离。。。对不起,如果没有道理的话。会更新的,我是说只有一段距离?或者每个可能的重复对之间的距离is
不是唯一重复的部分,你没有说,is
也是一个输入。是的,就像@Dan所说的,你是如何获得配对的?当你说“相邻”时,你是指长度为2的子串,对吗?如果是这样,为什么只有是而不是si
和it
?对不起!我拿走了另一双。所以输入现在是aismeorisityou
,输出应该是6。我仍然认为这是您再次寻找的答案,只是为了澄清一下。输入为aismeorisityou
,输出为数字。6.它将返回每对字母的距离,因为你有2个i,它将至少返回2个结果是的,这是正确的行为。但我只能拿到6分吗?而不是其他。是什么让6与其他不同?
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.