我的问题是,我似乎找不到正确的方法来遍历subject2并挑选出重复的字符串。下面是我的方法:
nosubjects = []
subjects2 = ["hi","hi","bi","ki","si","bi","li"]
for i in subjects2:
if subjects2.count(i)==2:
nosubjects.extend(i)
print(nosubjects)
但是当我打印出来时,它看起来像这样:
['hi','hi']
['h', 'i', 'h', 'i','b', 'i']
['hi', 'i', 'h', 'i', 'b', 'i', 'b', 'i']
请帮助谢谢!
答案 0 :(得分:1)
使用collections.Counter
获取每个元素的计数,并仅获取计数超过1的元素。
from collections import Counter
subjects2 = ['hi', 'hi', 'bi', 'ki', 'si', 'bi', 'li']
nosubjects = [x for x, i in Counter(subjects2).items() if i > 1]
print(nosubjects)
# ['hi', 'bi']
答案 1 :(得分:0)
您的代码中的问题:
nosubjects
,这将导致它多次打印。使用sets
。首先获取列表中唯一的元素集,然后可以检查原始列表中集合中每个元素的计数是否超过1。
nosubjects = []
subjects2 = ['hi','hi','bi','ki','si','bi','li']
for i in set(subjects2):
if subjects2.count(i)>=2:
nosubjects.append(i)
print(nosubjects)
使用列表理解:
subjects2 = ['hi','hi','bi','ki','si','bi','li']
nosubjects = [i for i in set(subjects2) if subjects2.count(i) >=2]
print(nosubjects)