python-3.x 如何打印csv文件中某列的最长句子

smdnsysy  于 2022-12-15  发布在  Python
关注(0)|答案(2)|浏览(133)

我是python的新手,我真的很难解决这个问题。我有一个csv文件,有不同的列,标记为“height”“weight”“full_name”等。我试图创建一个函数,它将遍历full_name列并返回最长的名称。(因此,如果文件夹中最长的名称是Rachel Smith,我将尝试返回该值。)
下面是迄今为止运行得最好的代码:

import csv
file = "personal_data.csv"
f = open(file)
reader = csv.reader(f, delimiter=",")
col_index = next(reader).index('full_name')
highest = max(rec[col_index] for rec in reader)
print(highest) #using this statement to test if it works
f.close()

我想它不起作用了,因为它只打印了瑞秋,而不是她的全名,瑞秋·史密斯。

i5desfxk

i5desfxk1#

您可以尝试在max()函数中使用key=参数:

import csv

with open("personal_data.csv", "r") as f_in:
    reader = csv.reader(f_in, delimiter=",")
    col_index = next(reader).index("full_name")

    highest = max([rec[col_index] for rec in reader], key=len)  # <-- use key=len here

print(highest)  # using this statement to test if it works
f0brbegy

f0brbegy2#

使用csv.DictReader可以消除查找full_name列索引的需要。使用max()key参数可以使其返回值而不是值的长度。

import csv

with open('personal_data.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    longest_name = max([row['full_name'] for row in reader], key=len)

print(longest_name)

字符串
如果文件足够大,需要考虑内存使用情况,则使用map()itemgetter()获取名称,并将其作为可迭代参数传递给max()

import csv
import operator

with open('personal_data.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    names = map(operator.itemgetter('full_name'), reader)
    longest_name = max(names, key=len)

print(longest_name)

打包成函数:

import csv

def get_longest_value_from_col(filename, column_name):
    with open(filename, 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        longest_name = max([row[column_name] for row in reader], key=len)

    return longest_name

相关问题