重复列表操作

2024-06-16 11:43:06 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个列表中的元素,我想操纵,基本上我希望这样:

input:
my_list = ['Gold Trophy (January)', 'Gold Trophy (February)', 'Bronze Trophy 
(March)']

output:
['Gold Trophy x2', 'Bronze Trophy (March)']

如果有一个重复的公共字符串(比如Gold Trophy),我希望删除这两个元素,并生成一个新元素(Gold Trophy x(重复的数量))

以下是我目前掌握的情况:

my_list = ['Gold Trophy (January)', 'Gold Trophy (February)', 'Bronze Trophy 
(March)']

# function to count how many duplicates
def countX(my_list, myString): 
    count = 0
    for ele in my_list: 
        if (myString in ele): 
            count = count + 1
    return count 

myString = 'Gold Trophy'
real_count = (countX(my_list, myString))


print(*my_list, sep=', ')
print('duplicates = '+str(countX(my_list, myString)))

此时,此代码将运行并返回列表中指定字符串的重复数。关于从这里到哪里实现期望的输出有什么想法吗?谢谢!你知道吗


Tags: 字符串元素列表mycountlistduplicatesmarch
2条回答

这应该在不使用正则表达式的情况下工作。为了清楚地说明正在发生的事情,我发表了这些评论。你知道吗

from collections import Counter
my_list = ['Gold Trophy (January)', 'Gold Trophy (February)', 'Bronze Trophy (March)']
output_ls = []
trophy_ls = []
month_ls = []
trophy_cnt_dc = {}
for item in my_list:
    trophy_ls.append(item.split(' (')[0])
    month_ls.append(item.split(' (')[1])
# print(trophy_ls) >> ['Gold Trophy', 'Gold Trophy', 'Bronze Trophy']
# print(month_ls) >> ['January)', 'February)', 'March)']
trophy_cnt_dc = dict(Counter(trophy_ls))
#print(trophy_cnt_dc) >> {'Gold Trophy': 2, 'Bronze Trophy': 1}
for k,v in trophy_cnt_dc.items():
    if v > 1:
        output_ls.append(k+' x'+str(v))
    else:
        ind = trophy_ls.index(k)
        output_ls.append(k+' ('+month_ls[ind])
print(output_ls)

输出:

['Gold Trophy x2', 'Bronze Trophy (March)']

这是一个解决方案(请参阅注释以获得澄清)。注意,我使用了一个小技巧来拆分姓名和日期:我在(上拆分,然后在需要时还原它。可以做得更干净,但不清楚是否需要。你知道吗

my_list = ['Gold Trophy (January)', 'Gold Trophy (February)', 'Bronze Trophy (March)']

# Create map of tuples: (name, date)
pairs = [tuple(x.split('(')) for x in my_list]

# count the number of each name
counts = dict()
for (name, day) in pairs:
    counts[name] = counts.get(name, 0) + 1

# create a dictionary from initial list
# it doesn't matter how collisions are resolved
# the dictionary is required to process each name only once
init = dict(pairs)
res = []

# for each name:
#   if count is > 1, print the count
#   if count is 1, then print its date
for (name, date) in init.items():
    if counts[name] > 1:
        res.append(name + 'x' + str(counts[name]))
    else:
        res.append(name + '(' + date)
print(res)

相关问题 更多 >