0

我有一个nested_list看起来像

[
    ['"1"', '"Casey"', '176544.328149', '0.584286566204162', '0.415713433795838', '0.168573132408324'], 
    ['"2"', '"Riley"', '154860.665173', '0.507639071226889', '0.492360928773111', '0.0152781424537786'], 
    ['"3"', '"Jessie"', '136381.830656', '0.47783426831522', '0.52216573168478', '0.04433146336956'], 
    ['"4"', '"Jackie"', '132928.78874', '0.421132601798505', '0.578867398201495', '0.15773479640299'], 
    ['"5"', '"Avery"', '121797.419516', '0.335213073103216', '0.664786926896784', '0.329573853793568']
 ]

(我的真实nested_list名单很长)。我试图从每个子列表中提取 2 个数据,这就是我所做的

numerical_list = []
child_list = []
for l in nested_list: 
    child_list.append(l[1])
    child_list.append(float(l[2]))
    numerical_list.append(child_list)
print(numerical_list)

这给了我一个list index out of range错误child_list.append(l[1])。但是,如果我将其更改for l in nested_list:for l in nested_list[:4]:或长度内的任何范围,则nested_list它可以正常工作。这对我来说没有任何意义。有人可以帮我找出问题所在吗?谢谢~

4

1 回答 1

0

如果您只对前两个元素感兴趣,一种方法是使用try... except,另一种直接方法是检查列表的长度,如下所示。

这样,您只附加第一个和第二个元素存在的列表。

numerical_list = []
child_list = []
for l in nested_list: 
    if len(l>=3):
        child_list.append(l[1])
        child_list.append(float(l[2]))
        numerical_list.append(child_list)
print(numerical_list)
于 2018-12-18T11:34:30.127 回答