小编Vin*_*ink的帖子

字典键 * 值到 python 中的列表

我的字典如下:

the_dict = {'1': 2,
 '2': 4,
 '3': 3,
 '8': 3,
 '9': 3,
 '10': 4,
 '14': 4}
Run Code Online (Sandbox Code Playgroud)

我需要将键乘以值来创建一个长长的平面列表。我的尝试如下,但它搞砸了 10 和 14:

new_target = []
for k, v in zip(the_dict.keys(), the_dict.values()):
    new_target += list(k*v)
Run Code Online (Sandbox Code Playgroud)

此代码产生: ['1', '1', '2', '2', '2', '2', '3', '3', '3', '8', '8', '8', '9', '9', '9', '1', '0', '1', '0', '1', '0', '1', '0', '1', '4', '1', '4', '1', '4', '1', '4']

该代码很接近,但由于 10 和 14 上的以下行为,它不起作用;list("10" *2)产生['1', '0', '1', '0']而不是所需的['10', '10'] …

python dictionary list python-3.x

3
推荐指数
1
解决办法
82
查看次数

IndexError:列表索引超出范围-用虚拟变量填充

我有一个60,000个列表。每个列表的范围是2-5个值。

我需要用每个列表中的第三个值创建一个新列表。

该列表还需要保留60,000个条目。

如果使用第二个值进行此操作,则将执行以下操作:

big_list = [['this', 'is', 'a list'], ['list' 'two'], ['here', 'is', 'another one']]

new_list = [value[1] for value in big_list]
Run Code Online (Sandbox Code Playgroud)

并且new_list会是

['is', 'two', 'is']
Run Code Online (Sandbox Code Playgroud)

在实际程序中new_list,现在将是从每个列表中的第二个值创建的60,000个值的列表。new_list保持相同的长度很重要。

现在,因为如果我尝试,某些列表只有2个值长

new_list = [value[2] for value in big_list]
Run Code Online (Sandbox Code Playgroud)

我很好 IndexError: list index out of range

我需要结果是

['a list', 'dummy variable', 'another one']
Run Code Online (Sandbox Code Playgroud)

有什么办法可以为只有2个值的列表预设一个虚拟变量,而无需更改任何内容big_list?虚拟变量可以是随机字符串,也可以是列表中的先前值。如果我不清楚,请告诉我,谢谢您的帮助。

python list

0
推荐指数
1
解决办法
43
查看次数

标签 统计

list ×2

python ×2

dictionary ×1

python-3.x ×1