将第一个位置与列表中的下一个位置进行比较

2024-10-03 15:32:56 发布

您现在位置:Python中文网/ 问答频道 /正文

“大家好

我必须将列表中的一个位置与同一列表中的下一个位置进行比较。ls[0]与ls[1],ls[1]与ls[2]

我要做的是将列表与匹配的字符进行比较,如果匹配,则添加一个点,然后只打印一次重复的字母及其重复次数:

ls=“ddddtttdaatttaaauyuu”

输出必须是:

你是谁

431231313

我已经制定了以下代码:

n = "DDDDTTTDAATTTAAAUYUUU"
con = 1
a = ""
d = ""
for i in range(len(n)-1):
    if n[i] == n[i+1]:
        con += 1
    else:
        d += " " + str(n[i])
        a += " " + str(con)
        con = 1

print(d)
print(a)

输出:

D T D A T A U Y
4 3 1 2 3 3 1 1

如您所见,在我的代码输出中,最后一个字符[U]和数字[3]都丢失了

我的代码中缺少了什么使其正确工作,我感谢您的帮助


Tags: 代码in列表forlen字母range字符
3条回答

您可以使用^{}

>>> import itertools
>>> l = [(e,len(list(g))) for (e,g) in itertools.groupby(s)]
>>> l
[('D', 4), ('T', 3), ('D', 1), ('A', 2), ('T', 3), ('A', 3), ('U', 1), ('Y', 1), ('U', 3)]

如果需要两个单独的列表,可以使用“始终列表理解”来拆分它们

>>> [x for (x,y) in l]
['D', 'T', 'D', 'A', 'T', 'A', 'U', 'Y', 'U']
>>> [y for (x,y) in l]
[4, 3, 1, 2, 3, 3, 1, 1, 3]

与其他答案相比,重复代码更少。它实际上迭代了太多的一次,并在退出循环之前在最后一次迭代中写入挂起的累积结果

n = "DDDDTTTDAATTTAAAUYUUU"
con = 1
a = ""
d = ""
for i in range(len(n)): # do one more iteration
    if i < len(n) - 1 and n[i] == n[i+1]: # as long as we have not gone past the end of the string, and the char is identical to the next one
        con += 1
    else:
        d += " " + str(n[i])
        a += " " + str(con)
        con = 1

print(d)
print(a)
n = "DDDDTTTDAATTTAAAUYUUU"
con = 1
a = ""
d = ""
for i in range(len(n)-1):
    if n[i] == n[i+1]:
        con += 1
    else:
        d += " " + str(n[i])
        a += " " + str(con)
        con = 1

# you are just missing this 😁
# when the loop finishes you have to concatenate
# a and d also

d += " " + str(n[i])
a += " " + str(con)  

print(d)
print(a)
 D T D A T A U Y U
 4 3 1 2 3 3 1 1 3

相关问题 更多 >