gpt4 book ai didi

python - 将每个字母与下一个字母进行比较

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:10 25 4
gpt4 key购买 nike

我正在尝试将列表中的每个字母与下一个字母进行比较,如果减法小于 1,我希望打印被比较的数字。

lis=[2,3,5,6,7,8,0,4,2,5,6,8,9,4,2,]
for number in lis:
if lis[number+1]-lis[number]==1:
print (number)

输出是

2
3
0
4
2
9
4
2

代码完全跳过了5,6,7但是打印出的数字并不真正符合声明。谁能解释一下?提前致谢

最佳答案

您将列表的索引混淆了。

例如,列表的第一个元素的索引为 0 但值为 2。下一个元素的索引为 1 但值为 3。下一个元素的索引为 2 但值为 5。当您使用 lis[index],结果是一个值。

当您使用 for number in lis 时,它会迭代值,而不是索引。

这是一种实现我认为您想要的方法:

lis=[2,3,5,6,7,8,0,4,2,5,6,8,9,4,2,]
for index, value in enumerate(lis[:-1]): #don't go all the way to the end because you're comparing with the next
if lis[index+1]-value <= 1: #you wanted less than, right?
print (value)

关于python - 将每个字母与下一个字母进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55694276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com