我想列出如下清单
data2 = ['Run, Read', 'Sing, Read', 'Run, Sing, Read', 'Read']
从这个清单
data = [
{29: 'Run'},
{29: 'Read'},
{30: 'Sing'},
{30: 'Read'},
{31: 'Run'},
{31: 'Sing'},
{31: 'Read'},
{32: 'Read'}]
谁能帮我
人们,请正确阅读问题。OP正在询问如何使用相同的键将不同字典的字符串收集到单个字符串中。
我有点想知道您将如何获得像这样的词典列表,而不是类似的列表
data = [
{29: 'Run', 30: 'Sing', 31: 'Read', 32: 'Read'},
{29: 'Read', 30: 'Read', 31: 'Run'},
{31: 'Sing')]
基本上是一样的,但是那不是重点。
您可以通过以下操作轻松完成所需的操作:
data = [
{29: 'Run'},
{29: 'Read'},
{30: 'Sing'},
{30: 'Read'},
{31: 'Run'},
{31: 'Sing'},
{31: 'Read'},
{32: 'Read'}]
# Create empty dict for all keys
key_dct = {}
# Loop over all dicts in the list
for dct in data:
# Loop over every item in this dict
for key, value in dct.items():
# Add value to the dict with this key
key_dct.setdefault(key, []).append(value)
# Combine all items in key_dct into strings
data2 = [', '.join(value) for value in key_dct.values()]
# Print data2
print(data2)
输出: ['Run, Read', 'Sing, Read', 'Run, Sing, Read', 'Read']
请注意,即使某些字典包含多个项目,我的解决方案仍然有效。
编辑:如果要确定字符串的顺序也按键的数字顺序,则将data2
上面代码段中的创建替换为
# Sort items on their key values
items = list(key_dct.items())
items.sort(key=lambda x: x[0])
# Combine all items into strings
data2 = [', '.join(value) for _, value in items]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句