这是列表。
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/