gpt4 book ai didi

python - 删除或更改列表中的特定重复元素(并非所有重复元素)

转载 作者:太空宇宙 更新时间:2023-11-03 19:42:18 26 4
gpt4 key购买 nike

我正在尝试制作一些可以读取字符元素列表并准确告诉您每个元素重复了多少次的东西。我的想法是使用 for 循环和打印语句来浏览列表,告诉我我想要的信息。

这是我的第一个想法:

list = ["code", "this", "code"]

for i in range(len(list)):
list.count(list[i])
print("{} is repeated ".format(list[i]) + str(list.count(list[i])) + " times")

当我运行这段代码时,它打印了:

代码重复2次

重复1次

代码重复2次

现在,实现我的目标的下一步是停止“代码重复 2 次”打印两次。这就是我的麻烦的开始。我已经搜索了从列表中删除特定重复项的方法,但我发现的只是删除所有重复项的方法(我不希望这样做,因为这会使代码在超过列表的第一个元素后变得无用)。因此,我的问题如下:

打印重复语句后是否可以从列表中删除特定的重复元素?这意味着,一旦打印“代码重复 2 次”,列表将仅更改为 [“this”]。

是否可以更改特定重复元素的“值”?这意味着,一旦打印“代码重复 2 次”,列表就会更改(例如)为 [0, "this", 0],以便我可以使用 if 语句在元素为 = 时不打印任何内容= 0。

明确地说,我只是想知道:

-如果可能的话:我怎样才能改变我的编码来实现这一点。

-如果不可能:我可以做其他事情来实现我的目标。

最佳答案

使用set :

lst = ["code", "this", "code"]
for elem in sorted(set(lst), key = lambda x:lst.index(x)):
print(f"{elem} is repeated {lst.count(elem)} times")

或者,dict.fromkeys :

for elem in dict.fromkeys(lst):
print(f"{elem} is repeated {lst.count(elem)} times")

输出:

code is repeated 2 times
this is repeated 1 times

您还可以查看collections.Counter() :

from collections import Counter
frequency = Counter(lst)
for word, freq in frequency.items():
print(f"{word} is repeated {freq} times")

相同的输出。

你所说的在某种意义上也是可能的,但它看起来不像Pythonic,我也觉得没有必要,但这是代码。

警告:在迭代列表时修改列表是一个坏主意。

lst = ['code', 'this', 'code']
i = 0
while any(lst):
if lst[i] == None:
i += 1
continue
print(f"{lst[i]} is repeated {lst.count(lst[i])} times")
lst = [None if j == lst[i] else j for j in lst]
i += 1

输出相同。

关于python - 删除或更改列表中的特定重复元素(并非所有重复元素),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60357470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com