提问人:andyon98 提问时间:11/10/2023 更新时间:11/10/2023 访问量:47
如何将单个字符串的列表转换为具有单个整数值的列表列表
How do you cast a list of list of one single string as a list of lists with individual integer values
问:
我有一个问题,我有一些数据给了我一个列表列表,例如;
x = [['128, 0, 0, 508, 1023, 516, 510, 509, 515'], ['135, 0, 23, 308, 1023, 326, 330, 649, 526']]
我希望获取每个列表的第 6 个元素并将其作为整数存储在另一个列表中,以便我应该能够遍历尽可能多的内部列表并将第 6 个值放入另一个列表中,以便它填充整数值。
我怎样才能做到这一点?
我目前尝试了以下尝试的解决方案,但是这不起作用,因为拆分不是一个属性。
y = [int(elem) for elem in x.split(',') ]
答:
0赞
manucorujo
11/10/2023
#1
代码中的问题是,您正在尝试拆分列表 x 的整个列表,这是不可能的,因为 x 是一个字符串方法,而 x 是一个列表列表。为了实现您的目标,您应该遍历子列表,然后拆分每个子列表的第 6 个元素并将其转换为整数。下面是代码的更正版本:split()
x = [['128, 0, 0, 508, 1023, 516, 510, 509, 515'], ['135, 0, 23, 308, 1023, 326, 330, 649, 526']]
# Initialize an empty list to store the 6th elements as integers
result = []
for sublist in x:
# Split the sublist by ',' and take the 6th element, then convert it to an integer
sixth_element = int(sublist[0].split(',')[5])
result.append(sixth_element)
print(result)
1赞
Saint-malo
11/10/2023
#2
首先是:
y = [e[0].split(",") for e in x]
你得到: [['128', ' 0', ' 0', ' 508', ' 1023', ' 516', ' 510', ' 509', ' 515'], ['135', ' 0', ' 23', ' 308', ' 1023', ' 326', ' 330', ' 649', ' 526']]
然后:
[int(e[6]) for e in y]
给你 : [510, 330]
评论
1赞
CtrlZ
11/10/2023
e[6] 是第七项
评论
x
[int(elem[0].split(', ')[5]) for elem in x]