我想创建一个新列表,以便使用键来匹配角色。
例如两个列表:
[['9', u'bob'], ['18', u'alice']]
[['1', 'officer'], ['2', 'nurse'], ['9', 'teacher'],['18', 'unknown']]
我想要一个新列表,即:
[['9', u'bob', 'teacher'], ['18', u'alice' 'unknown']]
或
[[u'bob', 'teacher'], [u'alice' 'unknown']]
答案 0 :(得分:1)
d1 = dict([[9, u'bob'], [18, u'alice']])
d2 = dict([[1, 'officer'], [2, 'nurse'], ['9', 'teacher'],['18', 'unknown']])
d = []
for k in d1:
if str(k) in d2:
d.append((k, d1[k], d2[str(k)]))
答案 1 :(得分:0)
尝试一下:
names = [[9, u'bob'], [18, u'alice']]
roles = [[1, 'officer'], [2, 'nurse'], [9, 'teacher'],[18, 'unknown']]
mapper = dict(roles)
print([[x[0],x[1],mapper[x[0]]] for x in names])
假设角色中的数字是同一类型,即整数或字符串。在这种情况下,我将它们作为与名称匹配的整数。
答案 2 :(得分:0)
这是一个简单的解决方案-
list_1 = [[9, u'bob'], [18, u'alice']]
list_2 = [[1, 'officer'], [2, 'nurse'], [9, 'teacher'],[18, 'unknown']]
new_list = []
for i in list_1:
for j in list_2:
if i[0]==j[0]:
new_list.append([i[1],j[1]])
这是同一行,但它会将元素放入元组-
>> [(x[1], y[1]) for x in list_1 for y in list_2 if x[0] == y[0]]
[('bob', 'teacher'), ('alice', 'unknown')]
要获取列表列表-
>> [list(elem) for elem in [(x[1], y[1]) for x in list_1 for y in list_2 if x[0] == y[0]]]
[['bob', 'teacher'], ['alice', 'unknown']]
答案 3 :(得分:0)
L1 = [[9, u'bob'], [18, u'alice']]
L2 = [[1, 'officer'], [2, 'nurse'], ['9', 'teacher'],['18', 'unknown']]
final_List = []
for l1 in L1:
for l2 in L2:
if str(l1[0]) == l2[0]:
num_L = [l1[1],l2[1]]
final_List.append(num_L)
print(final_List)
---------
Output:
---------
[['bob', 'teacher'], ['alice', 'unknown']]