是否可以在Python上创建一个字典,用循环插入列表和值?
说我有两个看起来像这样的列表
for i in holders:
print(i)
...给出
[1, 1]
[1, 2]
[1, 3]
[1, 4]
[2, 1]
[2, 2]
[2, 3]
[2, 4]
[3, 1]
[3, 2]
[3, 3]
[3, 4]
[4, 1]
[4, 2]
[4, 3]
[4, 4]
[5, 1]
[5, 2]
[5, 3]
[5, 4]
和另一个
for row in myArray:
print(row)
['0.0', '0.0', 'NaN']
['1.0', '0.0', '1.0']
['2.0', '0.0', 'NaN']
['3.0', '0.0', 'NaN']
['0.0', '1.0', '2.0']
['1.0', '1.0', '3.0']
['2.0', '1.0', '4.0']
['3.0', '1.0', 'NaN']
['0.0', '2.0', '5.0']
['1.0', '2.0', '6.0']
['2.0', '2.0', '7.0']
['3.0', '2.0', 'NaN']
['0.0', '3.0', 'NaN']
['1.0', '3.0', 'NaN']
['2.0', '3.0', '8.0']
['3.0', '3.0', '9.0']
['0.0', '4.0', 'NaN']
['1.0', '4.0', 'NaN']
['2.0', '4.0', 'NaN']
['3.0', '4.0', '10.0']
我想在python中编写一个类似于
的字典Diction =
{ '[1,1]': '-1'
'[1,2]': '1'
......等等 如果第3行是NaN,我想写-1 如果它是一个真实的数字而不是我写的那个数字..
这有道理吗? 我花了几个小时思考和尝试,没有运气
答案 0 :(得分:1)
你可以写:
my_dict = {str(h):l[-1] if l[-1] is not 'NaN' else '-1' for h, l in zip(holders, myArray)}
此外,您应避免使用myArray
等标识符 - camelCase为considered bad Python style。
这会在用作密钥的字符串化列表中为您提供额外的空间,但我怀疑这不值得取出(即如果您打算检查其他字符串列表中的密钥,它会'我会为你创造更多的工作。)
答案 1 :(得分:0)
l = [[1, 1],[1, 2],[1, 3]]
l2= [['0.0', '0.0', 'NaN'],['1.0', '0.0', '1.0'],['2.0', '0.0', 'NaN'],['3.0', '0.0', 'NaN']]
d = {}
for k,v in zip(l,l2):
if v[-1] == "NaN":
d[str(k)] = '-1'
else:
d[str(k)] = v[-1]
{'[1, 2]': '1.0', '[1, 1]': '-1', '[1, 3]': '-1'}