如何将列表中的元素与下一个元素进行比较以查看它们是否相同?假设我有一个列表,我想用for循环遍历该列表,并打印出多少个数字,然后再输入不同的数字。
str_n = "5223888"
count = 1
#print(len(str_n))
number = [int(x) for x in str_n]
#print(number)
for i in number:
while number[i] == number[i+1]:
count+=1
i+=1
print(count, " ", i)
预期输出:
15221338
答案 0 :(得分:1)
错误
for i in number
时,将“ 2”重复两次,然后将“ 8”重复三次,这将导致错误的输出。count
初始化为零。for i in number
迭代number
中的值,而不是索引更正代码
您可以使用以下代码:
str_n = "5223888"
number = [int(x) for x in str_n]
for i in set(number):
print("Element " + str(i) + " occurs " + str(number.count(i)) + " times")
答案 1 :(得分:1)
我花了一些时间来了解您的要求。在您的情况下,最好使用while循环
str_n = "5223888"
#print(len(str_n))
number = [int(x) for x in str_n]
#print(number)
i=0;
while(i<len(number)):
storei=i
count = 1
while i+1<len(number) and number[i] == number[i+1] :
count+=1
i+=1
i+=1
print("number is "+str(number[storei])+" count is "+str(count)))
输出
number is 5 count is 1
number is 2 count is 2
number is 3 count is 1
number is 8 count is 3
编辑 在python3中打印您需要指定的输出
str_n = "522388"
#print(len(str_n))
number = [int(x) for x in str_n]
#print(number)
i=0;
while(i<len(number)):
storei=i
count = 1
while i+1<len(number) and number[i] == number[i+1] :
count+=1
i+=1
i+=1
#print("number is "+str(number[storei])+" count is "+str(count))
print(str(count)+str(number[storei]),end="")
在python 2中,您需要指定准确的输出,如
str_n = "522388"
import sys
#print(len(str_n))
number = [int(x) for x in str_n]
#print(number)
i=0;
while(i<len(number)):
storei=i
count = 1
while i+1<len(number) and number[i] == number[i+1] :
count+=1
i+=1
i+=1
#print("number is "+str(number[storei])+" count is "+str(count))
sys.stdout.write(str(count)+str(number[storei]))
答案 2 :(得分:0)
当您写for i in number
时,您可能是指for i in range(len(number))
,它将使i
成为number
列表中的 indices 。
话虽如此,您实际上并不需要索引;当您说for num in number
时,num
是列表中的实际数字。您可以在没有索引的情况下完成以下操作:
count = 0
current = number[0]
for num in number:
if num == current:
count += 1
else:
print(count, current)
current = num
count = 1
print(count, current) # print the last count
这给我们:
1 5
2 2
1 3
3 8