gpt4 book ai didi

python-3.x - 在超出范围的索引上打印 “no value”

转载 作者:行者123 更新时间:2023-12-03 07:57:16 25 4
gpt4 key购买 nike

这是我的代码:

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'}]

最佳答案

结合使用itertools.zip_longestdict
例如:

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'}]

关于python-3.x - 在超出范围的索引上打印 “no value”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57553408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com