例如,如果我的嵌套列表是:
[['2HC'], ['4BB'], ['4BB'], ['2HC']]
如何将['2HC']
引用到'A'
,将['4BB']
引用到'B'
,这样我的结果将是:
['A', 'B', 'B', 'A']
答案 0 :(得分:1)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="show">
<span>Span text</span>
<span>Span text</span>
<span>Span text</span>
<select id="select1">
<option>1</option>
</select>
<select id="select2">
<option>1</option>
</select>
</div>
输出:
l = [['2HC',], ['4BB'], ['4BB'], ['2HC']]
mapping = {'2HC' : 'A', '4BB': 'B'}
new_list = [mapping[i[0]] for i in l]
print(new_list)
答案 1 :(得分:0)
l = [['2HC'], ['4BB'], ['4BB'], ['2HC']]
d = {'2HC' : 'A', '4BB': 'B'}
map(lambda x: d[x[0]], l)
# ['A', 'B', 'B', 'A']
答案 2 :(得分:0)
l = [['2HC'], ['4BB'], ['4BB'], ['2HC']]
lst = ['A' if x[0] == '2HC' else 'B' for x in l]
print(lst)
输出
['A', 'B', 'B', 'A']
答案 3 :(得分:0)
您可以拉平列表以使其更容易,然后使用简单的翻译映射:
from itertools import chain
nested_vs = [['2HC'], ['4BB'], ['4BB'], ['2HC']]
# flatten
vs = chain.from_iterable(nested_vs)
# translate
translations = {'2HC' : 'A', '4BB': 'B'}
translated = list(map(translations.get, vs))
现在translated
保持:
['A', 'B', 'B', 'A']
答案 4 :(得分:0)
针对此问题的itertools
解决方案-
data = [['2HC',], ['4BB'], ['4BB'], ['2HC']]
mapping = {'2HC' : 'A', '4BB': 'B'}
l = [mapping[i] for i in itertools.chain.from_iterable(data)]
itertools
的好处是,即使内部列表包含多个元素,它也可以将列表数据转换为平面列表。
例如,列表data
是-
[['2HC', '2HC'], ['4BB'], ['4BB'], ['2HC']]
我们仍然会获得正确的输出。