python - 从字符串集合中查找最大长度

标签 python

我正在努力解决这里的另一个问题,但遇到了一个不确定如何计算长度的步骤。

示例数据:

file_content = [
    '"Track","Artist","Album","Time"',
    '"Computer Love","Kraftwerk","Computer World","7:15"',
    '"Paranoid Android","Radiohead","OK Computer","6:27"'
]

目标:
计算具有最长字符长度的行并返回该值。基本上,从集合中找到 dict.values() 的字符总和以及 that 的最大值。

我尝试使用嵌套理解,但我陷入了困境。这是我到目前为止所尝试过的:

import csv
rows = [r for r in csv.DictReader(file_content)]
max([sum(len(v)) for row in rows for v in row.values()])

最佳答案

使用 Pandas

由于 csv 包含表格结构,我们也可以使用 pandas。

import pandas as pd
<小时/>

可以使用df = pd.read_csv(path)加载文件,它返回以下DataFrame:

Track                      Artist     Album           Time
Computer  Love             Kraftwerk  Computer World  7:15
Paranoid  Android          Radiohead     OK Computer  6:27

然后我们可以连接行并取组合字符串长度的最大值

df["Concat"] = [''.join(row.astype(str)) for row in df.values]

Track           Artist      Album           Time    Concat
Computer Love   Kraftwerk   Computer World  7:15    Computer LoveKraftwerkComputer World7:15
Paranoid Android    Radiohead   OK Computer 6:27    Paranoid AndroidRadioheadOK Computer6:27

df["Concat"].str.len().max()
#40

关于python - 从字符串集合中查找最大长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53506440/

相关文章:

python - 语法无效 - 表达式返回 f-String 中的字符串

python - 在用户输入后,如何更改 QButtongroup 元素中 QPushbutton 中的文本?

python - Paramiko 错误 : Error reading SSH protocol banner

python - python 中的 GC : what will this behave?

python - 使用 zip 将元组按顺序附加到列表内的列表的更好方法

python - 在python列表理解中分配中间变量

python - 如何删除字典中的键值?

python - FastICA 在真实录音中无法分离声音信号

python - 从导入的模块编辑类

python - 如何在Azure上运行Python3项目?