gpt4 book ai didi

python - 将值添加到列表并将类型更改为 int

转载 作者:行者123 更新时间:2023-11-30 21:53:07 26 4
gpt4 key购买 nike

我正在抓取一个页面,该页面有时会给我一个包含 5 个值的列表,有时会少于这个值。我需要格式化这些列表,以便它们都有 5 个值,而且都是整数。这些列表稍后将添加到 JSON,因此它们需要遵循相同的模式。

但我无法做到这一点。这些值没有按预期更改为整数。

示例和预期

scraped alement:  
all_lst = [['\n 35,726\n ',
'\n 61\n ',
8764,
'\n 11,756\n ',
'\n 3,417\n '],
['\n 185,620\n ',
'\n 116\n ',
41823]]

expected result:
all_lst = [[35726, 61, 8764, 11756, 3417], [185620, 116, 41823, 185620, 116]]

我尝试过的

for lst in all_lst:

if len(lst) == 5:
for i in range(5):
if type(lst[i]) == str:
lst[i] = int(lst[i].replace(' ','').replace('\n','').replace(',',''))
else:
lst[i] = lst[i]
else:
lst = list(islice(cycle(lst), 5))
for i in range(5):
if type(lst[i]) == str:
lst[i] = int(lst[i].replace(' ','').replace('\n','').replace(',',''))
else:
lst[i] = lst[i]

现在的输出是[[35726, 61, 8764, 11756, 3417], ['\n 185,620\n ', '\n 116\n ', 41823]]

最佳答案

您可以使用像这样的嵌套列表理解:

[[int(str(i).replace(',', '')) for i in islice(cycle(l), 5)] for l in all_lst]

这将返回:

[[35726, 61, 8764, 11756, 3417], [185620, 116, 41823, 185620, 116]]

关于python - 将值添加到列表并将类型更改为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59751823/

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