我正试着把列表转换成字典。每个列表必须有两个元素,如果没有,它应该附加第二个元素‘无’。这就是我被困的地方。
表格的初步清单:
test = [['A', 27], ['B', 33], ['C', 42], ['D']]最后一本词典应采用以下形式:
dictionary = {'A': 27, 'B':33, 'C': 42, 'D': 'None'}我对编码很陌生,循环是我的一个弱点。我一开始是:
for n in range(0, len(test1)):
d = dict(test1[n])但我完全迷失了方向。
我的思维过程是:获取列表中的所有元素(每个子列表),并将“无”附加到任何一维元素中。我只是不知道该怎么做。
发布于 2019-11-15 05:33:18
弄明白了..。我想我的问题措辞有点差。问题的关键是迭代列表,以确保所有子列表包含2个元素。
# Declare test list
test = [['A', 27], ['B', 33], ['C', 42], ['D']]
# Create max len variable
max_len = max(len(item) for item in test)
# Verify all lists within test contain 2 elements
# If not, append 'none'
for item in test:
while len(item) < max_len:
item.append(None)
test
# Create dictionary from list
contacts_dict = dict(test)
contacts_dict发布于 2019-11-15 05:39:25
你可以一边过滤一边过滤:
d = {x[0]: x[1] if len(x) == 2 else None for x in test}也可以使用dict构造函数:
d = dict(x if len(x) == 2 else (x[0], None) for x in test)https://stackoverflow.com/questions/58870249
复制相似问题