【问题标题】:How to create a two dimension list from a single dimension list by adding a new element?如何通过添加新元素从单个维度列表创建二维列表?
【发布时间】:2017-10-19 07:43:44
【问题描述】:

我有一个格式如下的列表:

flist = [1, 2, 4, 5, 418, 711, 736, 1389, 1478, 1582...]

我有代码来创建一个字典,其中包含“flist”上方列表中每个元素的内容:

test = " "
for x in (range(len(d[13]))):
    test += (d[13][x])
d[13] = test

例如,元素“13”的字典内容为:

d[13]
'  22\n\nLEARNING ON A GENERAL NETWORK\n\nAmir F. Atiya

现在,我想创建一个二维列表,其中: 1.列表“flist”的每个元素 2. 该特定元素的字典内容

到最后:

final = [1, "content from Dictionary for this element"],[2, "content from Dictionary for this element"],[4, "content from Dictionary for this element"],[],[]...

我试过了:

final = []
for x in range(len(flist)):
    flist[x].append(d[13])
AttributeError: 'numpy.int64' object has no attribute 'append'

但它不起作用。任何提示将不胜感激!

结果应该是数据框 pandas 格式: Column1:flist 中列表的元素 第 2 列。字典中该元素的内容

【问题讨论】:

  • flist[0] 不是一个列表。它只是一个没有append 属性的整数。
  • 你可以使用列表理解[[e, d[13]] for e in flist]
  • flist 不是列表...?
  • “特定元素的字典内容”是什么意思?每次都应该是d[flist[x]] 而不是d[13]
  • 我个人会有一个字典列表

标签: python list numpy dictionary


【解决方案1】:

我认为你想要的是列表理解

final = [[e, d[e]] for e in flist]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多