【问题标题】:list index out of range .what to do?列表索引超出范围。怎么办?
【发布时间】:2022-01-14 08:40:20
【问题描述】:

我的代码采用一系列数字并确定所有数字是否彼此不同:

lst=[]
while True:
    num=input('enter:')
    if num=='done':
        break
    n=int(num)
    lst.append(n)
print(lst)
c=0
lst1=lst
print(lst1)
for i in lst:
    for j in lst1:
        if lst[i] == lst1[j]:
            c+=1
if c==1:
    print("true")
else:
    print("false")

代码仅在满足(c==1) 时才有效,否则显示list is out of index in line 14

【问题讨论】:

  • ij 是通过 input() 获取的值。它们不是索引。因此,这些值可能会超出列表的范围
  • 您正在迭代 lst 的元素,然后尝试使用这些元素的值索引到同一个列表中。假设lst 包含值1000,这并不意味着lst[1000] 存在。您的代码中还有其他语义错误。

标签: python list loops for-loop if-statement


【解决方案1】:

如果你想知道一个整数列表是否只包含唯一的数字,那么你可以这样做:

mylistofnumbers = [1,2,3]

if len(mylistofnumbers) == len(set(mylistofnumbers)):
  print('Unique')
else:
  print('Not unique')

关键是集合只能包含唯一值。因此,如果集合的长度与列表的长度相同,那么列表必须只包含唯一的数字

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-04
    • 2020-11-05
    • 2018-12-16
    • 2011-06-14
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多