简体   繁体   English

命名元组的列表理解导致空列表

[英]List comprehension of namedtuples results in empty list

I've stumbled upon a problem I just can't seem to find an answer for. 我偶然发现了一个我似乎找不到答案的问题。 I am reading the contents of a csv file using csv.DictReader and constructing a list of namedtuples from that information. 我正在使用csv.DictReader读取csv文件的内容,并从该信息构造一个namedtuple列表。 However, upon running it, the end result is an empty list. 但是,运行它时,最终结果是一个空列表。

from collections import namedtuple
import csv

nt = namedtuple('suminfo', 'a, b, c')
checklist = ['check1', 'check2', 'check3']

with open('test.csv', 'r') as csv_file:
     csv_rows = csv.DictReader(csv_file, delimiter='\t')
     tups = [nt(row['first'], row['second'], row['third']) 
            for row in csv_rows if row['first'] in checklist]

I have also tried a typical normal loop of the rows followed by list appending of a namedtuple, and this seems to work just fine. 我还尝试了行的典型普通循环,然后对namedtuple进行列表附加,这似乎工作得很好。

Why is the listcomprehension not behaving as expected? 为什么列表理解不符合预期? Thank you for your time. 感谢您的时间。

The list comprehension is working for me. 列表理解为我工作。 I used this test data (test.csv): 我使用了以下测试数据(test.csv):

first   second  third
check1  1   1
check2  2   2
check3  3   3
check4  4   4

The values are separated by tabs. 这些值由制表符分隔。 When I run your code, 当我运行您的代码时,

nt = namedtuple('suminfo', 'a, b, c')
checklist = ['check1', 'check2', 'check3']

with open('test.csv', 'r') as csv_file:
    csv_rows = csv.DictReader(csv_file, delimiter='\t')
    tups = [nt(row['first'], row['second'], row['third']) 
            for row in csv_rows if row['first'] in checklist]
    print(tups)

I get the following result: 我得到以下结果:

>>> [suminfo(a='check1', b='1', c='1'), suminfo(a='check2', b='2', c='2'), suminfo(a='check3', b='3', c='3')]

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

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