获取" TypeError:' int'对象不可迭代"在尝试比较列表时

时间:2017-12-13 13:43:52

标签: python

我想知道我在下面的代码中做错了什么,我基本上试图采用用户输入的两个列表并使用union来创建一个包含来自2个用户列表的公共元素的新列表。有一次,当我得到错误时,我到达工会部分。

我的代码:

import random
import sys
import os

clear = lambda: os.system('cls')

x = 1

listA = []
listB = []
commlist = []

clear()
ammA = int(raw_input("How many elements do you want for your first     set?"))


clear()
while ammA > 0:
    listA.append(int(raw_input("Element %i :" %(x))))
    x = x+1
    ammA = ammA-1


clear()
ammB = int(raw_input("How many elements do you want for your second     set?"))

x = 1

clear()
while ammB > 0:
    listB.append(int(raw_input("Element %i :" %(x))))
    x = x+1
    ammB = ammB-1

commlist = list(set(ammA).union(set(ammB)))

clear()
print("Your two list are:")
print(listA)
print(listB)
print("The common elements are:")
print(commlist)

错误是:

Traceback (most recent call last):
  File "c:/Users/Bob/Documents/Intro To Python/Practice/Comparitor.py", line 39, in <module>
    commlist = list(set(ammA).union(set(ammB)))
TypeError: 'int' object is not iterable

1 个答案:

答案 0 :(得分:0)

问题在于您尝试使用整数变量创建集合,这些变量用于确定要放入列表中的元素数量,而不是列表本身。试试这个:

AnalysisException: u'expression `customer_ids` cannot be used as a grouping expression because its data type map<string,string> is not an orderable data type.

但请注意,对于常见元素,您可能需要>>> listA = [1,2,3,4,5] >>> listB = [1,3,5,7,9] >>> set(listA).union(set(listB)) {1, 2, 3, 4, 5, 7, 9} 而不是intersection

union