python - 使用字典列表中的特定值创建列表(键是字符串,值是整数列表)

标签 python string list dictionary

我有一个字典列表,其中包含一个字符串和一个字符串列表作为各自键的值:

list_of_dictionaries = [
    {'id': 'ABBA', 'num': ['10', '3', '5', '1']},
    {'id': 'ABAC', 'num': ['4', '5', '6', '20']}]

“id”字符串中的每个字母都与“num”中匹配索引处的数字相对应。因此,对于值“ABBA”,它将按顺序匹配每个位置的“num”中的值:A = 10、B = 3、B = 5、A = 1。我想返回带有“num”的 ids 列表> 每个字典中都有 5 个,同时保持其当前顺序。

这是我的尝试:

bad_values = ['','0','1','2','3','4','5']
final_ids =[]
for i in list_of_dictionaries:
     list_of_high_num =[]
     for id,num in enumerate(i.items()):
          if i["num"] is not bad_values:
             list_of_high_num.append(i["id"])
        final_ids.append(list_of_high_num)

但是,我只是将原始 ID 字符串放回到列表中。我哪里出错了?

所需的输出如下:

final_list = [['A'], ['A', 'C']]

最佳答案

考虑每个字典项的场景len(id) = len(num)

list_of_dictionaries = [
    {'id': 'ABBA', 'num': ['10', '3', '5', '1']},
    {'id': 'ABAC', 'num': ['4', '5', '6', '20']}]

limit = 5

outerlist = []
for d in list_of_dictionaries:
    innerlist = []
    for x in range(len(d['num'])):
        if int(d['num'][x]) > limit:
            innerlist.append(d['id'][x])
    outerlist.append(innerlist)

print(outerlist) # [['A'], ['A', 'C']]

关于python - 使用字典列表中的特定值创建列表(键是字符串,值是整数列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63941794/

相关文章:

python - 使用 python-pptx 从现有图表中读取图表数据

python - 使用 Python 快速查找文件的独立于操作系统的方法

python - 在 Python 中分配函数

python - Paho MQTT 无法与 Flask(Google 应用程序引擎)一起使用

java - 在每个单词后打印空格

python - 使用和不使用 ':' 运算符删除 python 中的列表

java - Java 字符串搜索期间突然变慢和 java.lang.OutOfMemoryError

Python - 将 2D 坐标对列表转换为 2 个 X 和 Y 分量列表

jquery - 如何在jquery中动态排序列表项?

c - 创建列表并打印其元素时出错