Python:在一个列表中找到相应的元素,并在一个新的lis中汇总它们

2024-04-18 21:43:39 发布

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

我有一个字符串列表,其中字符串的第一部分是列表中其他元素的子字符串。 我的目标是找到所有类似的字符串,即带有“ID\u 1”子字符串的元素,将它们添加到一个列表中,然后在“=”后面加上它们各自的值。你知道吗

示例:

start_list = ['ID_1=1', 'ID_1=2', 'ID_1=3', 'ID_2=4', 'ID_2=5', 'ID_2=6']

我试过用for循环迭代start\列表,创建各种嵌套列表,甚至尝试字典,但我一直在循环。你知道吗

我知道有一个很好的解决办法。你知道吗

我期望的结果是:

ID_1 = 6
ID_2 = 15

提前谢谢!你知道吗


Tags: 字符串id元素示例目标列表for字典
3条回答

鉴于这是你的第一个问题,我的方法是尽量简单和直接,并提出了许多意见,详细解释每一步。你知道吗

虽然提供更复杂或pythonic代码是一个更好的解决方案,但它最终可能会为您提供自己无法轻松理解或自定义的代码。你知道吗

start_list = ['ID_1=1', 'ID_1=2', 'ID_1=3', 'ID_2=4', 'ID_2=5', 'ID_2=6']
print start_list

# Here I am preparing an empty dictionary to store the counted keys and values
counted = {}
# Now I iterate through every string in start_list
for item in start_list:
    # As 1st thing I will use split method to separate the current_key
    current_key = item.split("=")[0]
    # and the current value. 
    current_value = int(item.split("=")[1])
    # Then I check if current_key (e.g. ID_1) is present in the
    # count dictionary using "in"
    if current_key in counted:
        # If the key is present I update its value with the sum
        # of its old value + new one
        counted[current_key] = current_value + counted[current_key]
    else:
        # If the key doesn't exist it means that we are adding it
        # to the counted dictionary for the 1st time
        counted[current_key] = current_value 

# Job is done!
print counted

# It is now easy to iterate through counted dict for further manipulation
# for example let's print the number of hits for ID_1

# You can use items() to enumerate keys and values in a dictionary
for key, value in counted.items():
    if key == "ID_1":
        print("Found ID_1 value: " + str(value))

# To obtain the output in your requirement
for key in counted.keys():
    print( '%s = %d' %(key, counted[key]))

如果您想更多地了解split方法的工作原理,这里有一个很好的解释和示例:
https://www.w3schools.com/python/ref_string_split.asp

在其他的答案中,你会找到更简洁的方法来获得这个结果。你知道吗

因此,为了改进我编写的代码,我建议您在这里阅读更多关于列表理解的内容:
https://www.pythonforbeginners.com/basics/list-comprehensions-in-python

你可以用defaultdict来做这个。我发现它是最紧凑和正确的变种。你知道吗

代码:

from collections import defaultdict

start_list = ['ID_1=1', 'ID_1=2', 'ID_1=3', 'ID_2=4', 'ID_2=5', 'ID_2=6']

d = defaultdict(int)
lst = [item.split('=') for item in start_list]
for k, v in lst:
    d[k] += int(v)

print(d.items())

输出:

dict_items([('ID_1', 6), ('ID_2', 15)])

您可以迭代d.items以按所需格式打印数据。你知道吗

代码:

for k, v in d.items():
    print(f"{k}={v}")

输出:

ID_1=6
ID_2=15

您可以使用collections.Counter来跟踪总和。与functools.reduce结合使用,如果您愿意,甚至可以将此作为一行:

>>> from functools import reduce
>>> from collections import Counter
>>> start_list = ['ID_1=1', 'ID_1=2', 'ID_1=3', 'ID_2=4', 'ID_2=5', 'ID_2=6']
>>> reduce(lambda c, x: c.update({x[0]: int(x[1])}) or c,
...        (x.split("=") for x in start_list), collections.Counter())
...
Counter({'ID_1': 6, 'ID_2': 15})

(这里,or c使lambda返回c,而不是update的结果,即None

相关问题 更多 >