这是我的代码:
x = ['ann', 'D4B3', 'richard', 'A4N5', 'lily', 'M3L1', 'david', 'P4N5', 'bea', 'S3B2']
List = []
i = 0
while i < len(x):
a = 1
name_list = 'list' + str(a)
name_list = {
'wife_code': x[i+1],
'wife_list': x[i],
'husband_code': x[i+3],
'husband_list': x[i+2],
}
List.append(name_list)
a += 1
i += 4
print(List)
在运行代码时,它将引发“ IndexError:列表索引超出范围”。我知道该错误发生在第三循环中,因为它没有“ husband_code”和“ husband_list”。有没有办法在超出范围的索引上打印“无值”?
预期输出:
[{'wife_code': 'ann', 'wife_list': 'D4B3', 'husband_code': 'richard', 'husband_list': 'A4N5'},
{'wife_code': 'lily', 'wife_list': 'M3L1', 'husband_code': 'david', 'husband_list': 'P4N5'},
{'wife_code': 'bea', 'wife_list': 'S3B2', 'husband_code': 'no value', 'husband_list': 'no value'}]
答案 0 :(得分:0)
将itertools.zip_longest
与dict
一起使用
例如:
from itertools import zip_longest
x = ['ann', 'D4B3', 'richard', 'A4N5', 'lily', 'M3L1', 'david', 'P4N5', 'bea', 'S3B2']
result = []
keys = ['wife_list', 'wife_code', 'husband_list', 'husband_code']
for i in range(0, len(x), 4):
result.append(dict(zip_longest(keys, x[i:i+4], fillvalue='no value')))
print(result)
具有列表理解
例如:
result = [dict(zip_longest(keys, x[i:i+4], fillvalue='no value')) for i in range(0, len(x), 4)]
输出:
[{'husband_code': 'A4N5',
'husband_list': 'richard',
'wife_code': 'D4B3',
'wife_list': 'ann'},
{'husband_code': 'P4N5',
'husband_list': 'david',
'wife_code': 'M3L1',
'wife_list': 'lily'},
{'husband_code': 'no value',
'husband_list': 'no value',
'wife_code': 'S3B2',
'wife_list': 'bea'}]