Python 在字典中插入数组
我有3个阵列:Python 在字典中插入数组,python,arrays,dictionary,Python,Arrays,Dictionary,我有3个阵列: id_ = [1,2,3,4] names = ['Mark', 'Fred', 'Justin', 'Tim'] Jobs = ['Teacher', 'doctor', 'Coach', 'Fireman'] 我想用for循环将它们插入字典中,得到如下内容: {1: ('Mark', 'Teacher'), 2: ('Fred', 'doctor'), 3: ('Justin', 'Coach'), 4: ('Tim', 'Fireman')} 如何才能做到这一点?如果
id_ = [1,2,3,4]
names = ['Mark', 'Fred', 'Justin', 'Tim']
Jobs = ['Teacher', 'doctor', 'Coach', 'Fireman']
我想用for循环将它们插入字典中,得到如下内容:
{1: ('Mark', 'Teacher'), 2: ('Fred', 'doctor'), 3: ('Justin', 'Coach'), 4: ('Tim', 'Fireman')}
如何才能做到这一点?如果将列表压缩在一起,则可以通过添加带有I:n,j的dict条目对其进行迭代 输出:
{1: ('Mark', 'Teacher'), 2: ('Fred', 'doctor'), 3: ('Justin', 'Coach'), 4: ('Tim', 'Fireman')}
这将为每个名称添加编号名称、作业对:
dict = {}
i = 0 # or 1, if you prefer. but it's not proper to start a list from 1 when programming.
while i < len(names):
dict[i] = (names[i], Jobs[i])
i = i+1
但我更喜欢第一种方法,因为它不需要先列出数字。这也比zip函数可读性强得多。我必须对每一个进行-1运算,以使计数有效,因为他以1开始编号。>id_=[1,2,3,4]
>>>姓名=[“马克”、“弗雷德”、“贾斯汀”、“蒂姆”]
>>>乔布斯=[“老师”、“医生”、“教练”、“消防员”]
>>>口述、口述、工作
{1:'马克','老师',2:'弗雷德','医生',3:'贾斯汀','教练',4:'蒂姆','消防员'}
文件:
:请注意,zip要求所有列表的长度相同。如果不是,您可以使用。
这不是一个循环不,因为这不是正确的方法。我的方法更好,因为它不需要预先制作数字列表。@yes 1海报要求使用for循环;2 for循环不需要预先制作数字列表,例如rangex是generator@Woodford是的,但这到底是怎么回事。不再争论了。
dict = {}
i = 0 # or 1, if you prefer. but it's not proper to start a list from 1 when programming.
while i < len(names):
dict[i] = (names[i], Jobs[i])
i = i+1
for i in id_:
dict[i] = (names[i-1], Jobs[i-1])