【问题标题】:Python: Looping through a tuple, first element is incorrectPython:循环遍历一个元组,第一个元素不正确
【发布时间】:2019-09-17 10:22:35
【问题描述】:

如果我错过了这个问题的答案,我深表歉意。我在 Python 中使用 enumerate 遍历一个元组,并简单地调用一个元组的每个元素。对于第一个元素,只有== 1时,secon方法返回2而不是1。其他所有元素都正确显示

tup = (1,2,2,3,4,5)
for el in enumerate(tup):
    print(el[1])
for el in tup:
    print(tup[el])

使用 enumerate 的循环返回正确的结果: 1 2 2 3 4 5

但是第二个循环返回: 2 2 2 3 4 5

只有在第一个元素是 1 O_o 时才会发生这种情况。

【问题讨论】:

  • 在第二个循环中,您正在索引...tup[1]tup[2]、... == second_element、third_element,依此类推...
  • 你在问为什么会得到不同的结果?
  • @Bogda Doicin 是的

标签: python tuples enumerate


【解决方案1】:

您应该在第二个循环中打印el

tup = (1,2,2,3,4,5)
for el in enumerate(tup):
    print(el[1])
for el in tup:
    print(el)

否则在第一个循环中tup[el] 将打印第二个元素。 el 在第一个循环中的值为 1,所以 tup[el] = tup[1] = 2

【讨论】:

  • 那么如果 tup = (3,2,2,3,4,5),两个循环返回相同的结果怎么办?
  • enumerate 合乎逻辑。因为 tup[1] 又是 2
猜你喜欢
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
相关资源
最近更新 更多