如何将pop用于列表列表

2024-09-27 00:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

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]]

这是我拥有的列表列表,我需要获取列表列表中每个列表的第一个值,并将其存储到列表中

我想我可以用流行音乐,但那只是第一个列表。结果是只打印出列表的第一个值,即第一个列表

有什么建议吗?我在想可能是for循环,但我不知道如何格式化它


Tags: csvtxt列表fordefaswithopen
3条回答

由于您只需要第一个元素,因此可以使用内置函数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]) 

这将遍历listoftimecards中的每个项,并将listoftimecards中每个列表的第一项追加到list1

下面的代码执行与上面代码相同的操作

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

相关问题 更多 >

    热门问题