【问题标题】:Python list of numbers and returns another list that contains only numbers that appear only oncePython 数字列表并返回另一个列表,该列表仅包含仅出现一次的数字
【发布时间】:2020-02-11 16:41:06
【问题描述】:

我在 python 2.7 中尝试这样做:
“编写一个程序,接受一个数字列表并返回另一个列表,其中仅包含只出现一次的数字”
这是我的代码

list1 = [1,2,3,4,3,6,1,8,9,10,3,50]
list1.sort()
lst = set()
for i in xrange(len(list1)):
    if( int(list1[i]) == int(list1[i+=1]) ):
        continue
    else:
        lst.add(list1[i])

print (lst)

我得到了这个错误输出:

 if( int(list1[i]) == int(list1[i+=1]) ):
                                     ^
SyntaxError: invalid syntax

【问题讨论】:

  • 试试这个lst=set(list1)。
  • i+=1 是一个赋值statement,你需要一个表达式。试试i+1。
  • 为什么还是 python 2.7? python 2.7的time has run out.
  • 这是否意味着“识别列表中模式 = 1 的数字”或“生成所有存在的数字的列表,仅表示一次”?
  • 2.7 因为我在上大学(不知道为什么)问题还是没有解决

标签: python list python-2.7 numbers tuples


【解决方案1】:

您可以使用一个列表来存储您已经迭代过的所有数字,并检查该列表以查看是否已经插入了一个数字:

list1 = [1,2,3,4,3,6,1,8,9,10,3,50]
dups = []
result = []
for elem in list1:
  if not elem in dups:
    result.append(elem)
    dups.append(elem)

print result

这将返回:

[1, 2, 3, 4, 6, 8, 9, 10, 50]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2020-02-13
    相关资源
    最近更新 更多