list - 如果列表重复n次,如何删除列表中的所有字母。其中 n 是 1-10 之间的数字

标签 list python-3.x for-loop

这是列表。

list1 =['F', 'L', 'Y', 'W', 'B', 'E', 'G', 'A', 'L', 'K', 'R', 'U', 'B', 'E', 'T', 'L', 'H', 'G', 'E', 'C', 'K', 'Y', 'U', 'B', 'H', 'L', 'U', 'G', 'A', 'F', 'K', 'Y', 'F', 'M', 'P', 'U', 'B', 'K', 'F', 'G', 'I', 'O', 'N', 'S', 'Y']

我想删除重复n次的字母。在这个问题的上下文中,n 是 4。

这是我到目前为止所尝试过的。

n = 4
alphabet = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
i = 0
for x in range(len(alphabet)-1):
    print(alphabet[i])
    h = list1.count(alphabet[x])
    print("h: ",h)
    if h == n:
        while alphabet[x] in alphabet:
            alphabet.remove(alphabet[x])
print(alphabet)

I 收到一条错误消息,指出 list.remove(x): x not in list

最佳答案

to delete the letters that repeat n numbers of time

使用 collections.Counter 的解决方案子类:

import collections

n = 4
list1 =['F', 'L', 'Y', 'W', 'B', 'E', 'G', 'A', 'L', 'K', 'R', 'U', 'B', 'E', 'T', 'L', 'H', 'G', 'E', 'C', 'K', 'Y', 'U', 'B', 'H', 'L', 'U', 'G', 'A', 'F', 'K', 'Y', 'F', 'M', 'P', 'U', 'B', 'K', 'F', 'G', 'I', 'O', 'N', 'S', 'Y']
counts = collections.Counter(list1)
list1 = [l for l in list1 if l in counts and counts[l] != n]

print(list1)

输出:

['W', 'E', 'A', 'R', 'E', 'T', 'H', 'E', 'C', 'H', 'A', 'M', 'P', 'I', 'O', 'N', 'S']

关于list - 如果列表重复n次,如何删除列表中的所有字母。其中 n 是 1-10 之间的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42614922/

相关文章:

Java:如何按列表的大小对列表列表进行排序?

python - 展开嵌套的 Python 字典

javascript - 将 django 模板变量传递给 js 数据表

python - Matlab 用 For 循环连接行向量

python - Python 中的列表理解 : do extra for loop if condition is verified otherwise don't make extra for loop

c++ - 当我们在 for 循环条件中使用 cin 时发生了什么?

python - 在 Python 中使用星号显示用户输入数字的条形图

python - python中获取类对象的生命周期

python - 如何在 python 中找到函数对象的必需参数?

list - 将列表传递给 QR 生成器