我竭尽全力寻找其他答案,但是我没有设法找到解决方法。
我有一本这样的字典:
namedict = {'0': 'female\tLotta\tAskildsen', '1': 'male\tHendrich\tDyb', '2': 'female\tRut\tAase', '3': 'male\tSigve\tBuer', '4': 'female\tBetina\tDimmen', '5': 'male\tOsvald\tAndvik', '6': 'female\tGunnbjørg\tAarset', '7': 'male\tMorten\tAlm', '8': 'female\tInes\tAbelsen', '9': 'male\tStian\tBerthelsen', '10': 'male\tGulbrand\tBrekka', '11': 'male\tHåvar\tClaussen', '12': 'female\tThi\tAslam', '13': 'female\tAslaug\tDuong', '14': 'female\tTora\tChristensen', '15': 'male\tLucas\tDrevland', '16': 'male\tOluf\tBirkedal', '17': 'male\tHalvar\tByberg', '18': 'male\tLeif\tBach', '19': 'female\tAyse\tBaltzersen', '20': 'female\tAnastasia\tBergli', '21': 'male\tRonald\tAasberg', '22': 'female\tElly\tDehli', '23': 'female\tElizabeth\tAalberg', '24': 'male\tRunar\tAsk'}
我想做的是使用另一个列表:
mylist = ['16', '17', '18', '19', '20', '21', '22', '23', '15']
并获得一个新列表,其名称与namedict中的key:value对应。
赞:
newlist = ['Oluf\tBirkedal', 'Halvar\tByberg', 'Leif\tBach', --->]
我试图将新列表转换为元组,但是我不明白如何将元组用作字典中的键。
感谢任何帮助!
答案 0 :(得分:1)
将dict.get
与list comprehesion
一起使用:
newlist = [namedict.get(value).split('\t',1)[1] for value in mylist]
print(newlist)
['Oluf\tBirkedal',
'Halvar\tByberg',
'Leif\tBach',
'Ayse\tBaltzersen',
'Anastasia\tBergli',
'Ronald\tAasberg',
'Elly\tDehli',
'Elizabeth\tAalberg',
'Lucas\tDrevland']
答案 1 :(得分:1)
下面也是执行此操作的另一种方法。
namedict = {'0': 'female\tLotta\tAskildsen', '1': 'male\tHendrich\tDyb', '2': 'female\tRut\tAase', '3': 'male\tSigve\tBuer', '4': 'female\tBetina\tDimmen', '5': 'male\tOsvald\tAndvik', '6': 'female\tGunnbjørg\tAarset', '7': 'male\tMorten\tAlm', '8': 'female\tInes\tAbelsen', '9': 'male\tStian\tBerthelsen', '10': 'male\tGulbrand\tBrekka', '11': 'male\tHåvar\tClaussen', '12': 'female\tThi\tAslam', '13': 'female\tAslaug\tDuong', '14': 'female\tTora\tChristensen', '15': 'male\tLucas\tDrevland', '16': 'male\tOluf\tBirkedal', '17': 'male\tHalvar\tByberg', '18': 'male\tLeif\tBach', '19': 'female\tAyse\tBaltzersen', '20': 'female\tAnastasia\tBergli', '21': 'male\tRonald\tAasberg', '22': 'female\tElly\tDehli', '23': 'female\tElizabeth\tAalberg', '24': 'male\tRunar\tAsk'}
mylist = ['16', '17', '18', '19', '20', '21', '22', '23', '15']
new_list = [(namedict[i].split("\t")[1]+"\t"+namedict[i].split("\t")[2]) for i in mylist]
print(new_list)
输出:
['Oluf\tBirkedal', 'Halvar\tByberg', 'Leif\tBach', 'Ayse\tBaltzersen', 'Anastasia\tBergli', 'Ronald\tAasberg', 'Elly\tDehli', 'Elizabeth\tAalberg', 'Lucas\tDrevland']
答案 2 :(得分:0)
如果namedct
的值本身是字典,元组或命名元组,则将更加方便。
另外,如果您的键是从零开始的连续数字,则列表可能更合适,因此如下所示:
name_list = [
('male', 'Foo', 'Bar'),
('female', 'Spam', 'Baz'),
# ...
]
然后您可以像这样提取mylist
中的索引值:
[name_list[i][1:] for i in mylist]
如果要保留制表符:
['\t'.join(name_list[i][1:]) for i in mylist]