简体   繁体   English

如何将 pop 用于列表列表

[英]How to use pop for a list of lists

def process_timecards():
    timecards = []
    with open("timecards.txt") as f:
        reader = csv.reader(f)
        listoftimecards = [list(map(float,row)) for row in reader]
    print(listoftimecards)
    list1 = listoftimecards.pop(0)
    print(list1)
[[688997.0, 5.0, 6.8, 8.0, 7.7, 6.6, 5.2, 7.1, 4.0, 7.5, 7.6], [939825.0, 7.9, 6.6, 6.8, 7.4, 6.4, 5.1, 6.7, 7.3, 6.8, 4.1], [900100.0, 5.1, 6.8, 5.0, 6.6, 7.7, 5.1, 7.5], [969829.0, 6.4, 6.6, 4.4, 5.0, 7.1, 7.1, 4.1, 6.5], [283809.0, 7.2, 5.8, 7.6, 5.3, 6.4, 4.6, 6.4, 5.0, 7.5], [224568.0, 5.2, 6.9, 4.2, 6.4, 5.3, 6.8, 4.4], [163695.0, 4.8, 7.2, 7.2, 4.7, 5.1, 7.3, 7.5, 4.5, 4.6, 7.0], [454912.0, 5.5, 5.3, 4.5, 4.3, 5.5], [285767.0, 7.5, 6.5, 6.3, 4.7, 6.8, 7.1, 6.6, 6.6], [674261.0, 7.2, 6.2, 4.9, 6.5, 7.2, 7.5, 5.0, 7.9], [426824.0, 7.4, 6.5, 5.7, 8.0, 6.9, 7.5, 6.5, 7.5], [934003.0, 5.8, 7.5, 5.8, 4.8, 5.9, 4.8, 4.0, 6.6, 5.5, 7.2]]

This is the list of lists that I have, and i need to grab the first value of each list inside of the list of lists and store that into a list.这是我拥有的列表列表,我需要获取列表列表中每个列表的第一个值并将其存储到列表中。

I thought i could use pop, but that only goes to the first list.我以为我可以使用 pop,但这只会出现在第一个列表中。 It results in just printing out the first value of the list, which is the first list.结果只是打印出列表的第一个值,即第一个列表。

Any advice?有什么建议吗? I was thinking maybe a for loop, but i have no idea how i would format it.我在想可能是一个 for 循环,但我不知道如何格式化它。

list1 = [sublist[0] for sublist in listoftimecards]

since you want only the first element you could grab from each row only the first element using the built-in function next :由于您只需要第一个元素,因此您可以使用内置函数next从每一行中抓取第一个元素:

def process_timecards():
    timecards = []
    with open("timecards.txt") as f:
        reader = csv.reader(f)
        list1 = [next(map(float,row)) for row in reader]
    print(list1)
list1 = []
for item in listoftimecards:
    list1.append(item[0]) 

This loops through each item in listoftimecards and appends the first item of every list in listoftimecards to list1这个循环遍历每个项目listoftimecards并附加在每个列表的第一项listoftimecardslist1

This code below does the same thing as the code above.下面的这段代码与上面的代码做同样的事情。

list1 = [x[0] for x in listoftimecards]

In Python 2, you can use:在 Python 2 中,您可以使用:

map(lambda lst:lst[0], listoftimecards)

In Python 3, map returns you a generator so you need to call list():在 Python 3 中,map 会返回一个生成器,因此您需要调用 list():

list(map(lambda lst:lst[0], listoftimecards))

but if you only wish to iterate the result using map will be memory efficient.但是如果您只想使用 map 迭代结果将是内存高效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM