我有一个表格的数据列表:
[line1,a]
[line2,c]
[line3,b]
我想使用 a=5、c=15、b=10 的映射:
[line1,5]
[line2,15]
[line3,10]
我正在尝试使用这段代码,我知道它是不正确的,有人可以指导我如何最好地实现这一点:
mapping = {"a": 5, "b": 10, "c": 15}
applyMap = [line[1] = 'a' for line in data]
谢谢
编辑: 只是在这里澄清一下,对于一行,但是我希望这个映射发生在文件中的所有行:
输入:["line1","a"]
输出:["line1",5]
最佳答案
您可以尝试使用列表理解。
lines = [
["line1", "much_more_items1", "a"],
["line2", "much_more_items2", "c"],
["line3", "much_more_items3", "b"],
]
mapping = {"a": 5, "b": 10, "c": 15}
# here I assume the key you need to remove is at last position of your items
result = [ line[0:-1] + [mapping[line[-1]] for line in lines ]
关于python映射字典到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9886249/