P.S: Thank you everybody ,esp Matthias Fripp . Just reviewed the question You are right I made mistake : String is value not the key
num=[1,2,3,4,5,6]
pow=[1,4,9,16,25,36]
s= ":subtraction"
dic={1:1 ,0:s , 2:4,2:s, 3:9,6:s, 4:16,12:s.......}
有一种简单的方法可以将两个列表转换成字典:
newdic=dict(zip(list1,list2))
但是对于这个问题,即使有了理解也没有任何线索
print({num[i]:pow[i] for i in range(len(num))})
答案 0 :(得分:0)
原则上,这将满足您的要求:
nums = [(n, p) for (n, p) in zip(num, pow)]
diffs = [('subtraction', p-n) for (n, p) in zip(num, pow)]
items = nums + diffs
dic = dict(items)
但是,词典中不能有多个具有相同键的项,因此您的每个“减法”项都将被添加到词典中的下一项代替,而您只会得到最后一项。因此,您可能希望直接使用items
列表。
如果您需要按照显示的顺序对items
列表进行排序,这将需要更多的工作。也许是这样的:
items = []
for n, p in zip(num, pow):
items.append((n, p))
items.append(('subtraction', p-n))
# the next line will drop most 'subtraction' entries, but on
# Python 3.7+, it will at least preserve the order (not possible
# with earlier versions of Python)
dic = dict(items)
答案 1 :(得分:0)
正如其他人所说,dict
不能包含重复的密钥。您可以通过一些调整使密钥重复。我使用OrderedDict
来保持插入键的顺序:
from pprint import pprint
from collections import OrderedDict
num=[1,2,3,4,5,6]
pow=[1,4,9,16,25,36]
pprint(OrderedDict(sum([[[a, b], ['substraction ({}-{}):'.format(a, b), a-b]] for a, b in zip(num, pow)], [])))
打印:
OrderedDict([(1, 1),
('substraction (1-1):', 0),
(2, 4),
('substraction (2-4):', -2),
(3, 9),
('substraction (3-9):', -6),
(4, 16),
('substraction (4-16):', -12),
(5, 25),
('substraction (5-25):', -20),
(6, 36),
('substraction (6-36):', -30)])
答案 2 :(得分:-1)
list1=[1,2,3,4]
list2=[4,5,6,7]
strings="8901"
list1.append(list.2)
strings=strings+ str(list1)