简体   繁体   English

如何遍历字符串并查找重复的值

[英]How to iterate through a string and find the duplicated values

My question is that I can't seem to find the right method for iterating through subjects2 and pick out the duplicated strings. 我的问题是,我似乎找不到正确的方法来遍历subject2并挑选出重复的字符串。 Below is my method: 下面是我的方法:

nosubjects = []
subjects2 = ["hi","hi","bi","ki","si","bi","li"]
for i in subjects2:
  if subjects2.count(i)==2:
    nosubjects.extend(i)
    print(nosubjects)

But when I print it out it appears like this: 但是当我打印出来时,它看起来像这样:

['hi','hi']
['h', 'i', 'h', 'i','b', 'i']
['hi', 'i', 'h', 'i', 'b', 'i', 'b', 'i']

Please help thanks! 请帮忙谢谢!

Use collections.Counter to get count of each element and take only those whose count exceeds 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']

Problems in your code: 您的代码中的问题:

  • You are trying to check the count of each element in the list, due to which duplicated elements will be checked multiple times. 您正在尝试检查列表中每个元素的计数,因为它将多次检查重复的元素。
  • You are printing nosubjects inside the if condition which will cause it to be printed multiple times 您正在if条件内打印无nosubjects ,这将导致它多次打印

Use sets . 使用sets First to get unique set of elements in the list, then you can check if the count of each element in the set exceeds 1 in the original list. 首先获取列表中唯一的元素集,然后可以检查原始列表中集合中每个元素的计数是否超过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)

Using list comprehension: 使用列表理解:

subjects2 = ['hi','hi','bi','ki','si','bi','li']

nosubjects = [i for i in set(subjects2) if subjects2.count(i) >=2]    
print(nosubjects)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何遍历顺序字符串值并附加到嵌套列表 - How to iterate through sequential string values and append to a nested list 需要迭代字典才能找到字符串片段 - need to iterate through dictionary to find slice of string 如何遍历值是元组的字典熊猫并找到第一个True和False值 - How to iterate through a dictionary pandas where values are tuples, and find first True and False values 如何遍历目录以查找文件夹 - How to iterate through directory to find folders 如何遍历数据框并找到字符串的特定部分并将其添加为新列? - How to iterate through a dataframe and find a specific part of a string and add it too a new column? 清理数据:如何遍历列表查找项目是否包含字符串,空格或空格,然后在Python中删除该项目 - Cleaning data: How to iterate through a list find if item contains a string, whitespace or blank and delete that item in Python 如何使用列表作为值遍历字典 - How to iterate through dictionary with lists as values 如何遍历列表并使用.strip()更新值 - How to iterate through a list and update values with .strip() python - 如何遍历 dict 的值 - python - how to iterate through values of dict 如何遍历 dataframe 中的列并更新值? - How to iterate through columns in a dataframe and update the values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM