在给定两个列表的情况下,已经出现了一个问题,它返回在两个列表中多次出现的所有元素的列表。返回的列表应按升序排列,不能重复。您的主程序将允许在一行中输入两个数字列表,并用分号分隔,最后输入一个空行。例如
列表:1 3 4 2 1 2 1 3; 4 4 2 4 3 2 4 4 3 1 3
列表1:1 3 4 2 1 2 1 3
列表2:4 4 2 4 3 3 2 4 4 3 1 3
此示例的结果为:[2,3]
我的大部分编程工作都在进行,只是在计算器函数中实现了第一个for循环后,我得到了一个错误。 ValueError:int()以10为底的无效文字:“ 3;”
由于我的经验不足,某处可能存在语法错误。任何帮助或建议,我们将不胜感激。
def calculator(userinput):
marker = ":"
for x in userinput:
if x == ";":
marker = ";"
elif marker != ";":
numlist1 = [int(x) for x in userinput]
elif marker == ";": numlist2
numlist2 = [int(x) for x in userinput]
else:
pass
for y in numlist1:
list1 = numlist1.count(y)
list2 = numlist2.count(y)
if list1 > 1 and list2 > 1:
if y not in multiples:
multiples.append(int(y))
else:
continue
multiples.sort()
print(multiples)
while True:
multiples = []
userinput = input("Lists: ").split() # asks for first input from user
if len(userinput) == 0: # breaks if user inputs nothing
break
calculator(userinput) # calls the calculator function
答案 0 :(得分:0)
我相信这可以满足您的需求……
$ cat intersec_two_list.py
#!/bin/env python
import sys
import collections
def intersect_list(lst1, lst2):
return sorted(list(set(lst1) & set(lst2)))
def find_mult(lst1, lst2):
c1 = collections.Counter(lst1)
mc1 = [mc[0] for mc in c1.items() if mc[1] > 1]
c2 = collections.Counter(lst2)
mc2 = [mc[0] for mc in c2.items() if mc[1] > 1]
return intersect_list(mc1, mc2)
def main(l1,l2):
print find_mult(l1,l2)
if __name__ == "__main__":
user_input = sys.argv[1:][0]
[s1, s2] = user_input.split(';')
s1 = s1.strip()
s2 = s2.strip()
l1 = s1.split(' ')
l2 = s2.split(' ')
main(l1,l2)
您将像这样执行...
$ ./intersec_two_list.py "1 3 4 2 1 2 1 3; 4 4 2 4 3 2 4 4 3 1 3"
['2', '3']
这是上面代码的一些解释:
def intersect_list(lst1, lst2):
return sorted(list(set(lst1) & set(lst2)))
在这种方法中,我set()
从列表中删除重复项。
>>> list = [ 1,2,3,3,3,3,4,5,6,6,6]
>>> set(list)
{1, 2, 3, 4, 5, 6}
然后我们像这样&
使用set(lst1) & set(lst2)
得到两个集合的交集,然后用list(set(lst1) & set(lst2))
将其转换回列表,然后返回sorted
列表
用这种方法...
def find_mult(lst1, lst2):
c1 = collections.Counter(lst1)
mc1 = [mc[0] for mc in c1.items() if mc[1] > 1]
c2 = collections.Counter(lst2)
mc2 = [mc[0] for mc in c2.items() if mc[1] > 1]
return intersect_list(mc1, mc2)
...使用Counter
的。计数器的作用是什么:
>>> from collections import Counter
>>> list1 = [1,2,3,3,3,3,4,5,6,6,6]
>>> Counter(list1)
>>> Counter({3: 4, 6: 3, 1: 1, 2: 1, 4: 1, 5: 1})
它计算列表的元素。这样,我们就可以摆脱掉列表中所有没有出现过的所有元素,就像这样:
mc1 = [mc[0] for mc in c1.items() if mc[1] > 1]
上面是此python代码的简称的列表理解:
mc1 = []
for mc in c1.items():
if mc[1] > 1:
mc1.append(mc[0])
然后上述代码的键是c1.items()
。 c1
是一个集合,集合具有方法items()
,该方法从集合中返回(elem, cnt)
对的列表。因此,if mc[1] > 1
表示该元素出现了多次,而mc[0]
是该元素。我们将这些元素保存在名为mc1
的列表中。
我们在lst2
上执行相同的过程。我们创建集合c2
,并创建列表mc2
。现在我们得到mc1
和mc2
的交集,并返回它和BAM!完成了。