[英]How to get the nth element of a list
I have the following output from my code: 我的代码有以下输出:
['test1', ':', '(', '83.25,', '78.32)', '*33.90*', '2.29', '2.14', '0.82', '65.95', 'test2', ':', '(', '101.80,', '95.10)', '*31.73*', '12.05', '0.60', '0.96', '-26.46', 'test3', ':', '(', '49.84,', '42.29)', '*33.19*', '6.54', '1.24', '0.50', '67.42']
I want the 6th, 7th, 16th, 17th, 26th and 27th element of the list and so on for any length If possible putting them in two separate lists. 我想要列表的第6、7、16、17、26和27个元素,依此类推,以任意长度,如果可能的话,将它们放在两个单独的列表中。 So eventually I would like an output that's just two lists like the following:
所以最终我希望输出的只是两个列表,如下所示:
list1 = [2.29, 12.05, 6.54]
list2 = [2.14, 0.60, 1.24]
Does anyone know how to get this result? 有谁知道如何得到这个结果?
If your list is called data
you can do the following. 如果您的列表称为
data
,则可以执行以下操作。
data_starting_at_position_6 = data[6::10]
data_starting_at_position_7 = data[7::10]
You start at the correct position and use 10
as the step. 您从正确的位置开始,并使用
10
作为步骤。
At the moment you have strings in the list, so data[6::10]
gives you ['2.29', '12.05', '6.54']
. 目前,列表中有字符串,因此
data[6::10]
为您提供['2.29', '12.05', '6.54']
。 If you would like to have floats you can use list(map(float, data[6::10]))
and get [2.29, 12.05, 6.54]
. 如果您想使用浮点数,则可以使用
list(map(float, data[6::10]))
并获得[2.29, 12.05, 6.54]
。
Use the mod of index! 使用索引的mod!
6_list = []
7_list = []
for i in xrange(len(your_list) + 1):
if i%10 == 6:
6_list.append(your_list[i])
elif i%10 == 7:
7_list.append(your_list[i])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.