统计lis中的符号和字符

2024-10-01 11:32:09 发布

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

假设我有下面的单词我想放在一个列表中

"cat,dog,fish"         (first row)
"turtle,charzard,pikachu,lame"    (second row)
"232.34,23.4,242.12%"           (third row)

我的问题是如何计算每行中的令牌,比如第一行有3个,第二行有4个,第三行有3个。在那之后,我如何计算字符数,然后决定每一行的字符数最多?所以输出看起来像

^{pr2}$

只使用len()等简单的列表方法。并使用逗号作为分隔符。每次我都会用逗号来代替我,因为我每次都会输


Tags: 列表字符单词catrowfirst逗号second
3条回答

给定字符串列表:

def my_output(string_of_tokens):
    tokens = string_of_tokens.split(",")
    print "token count = %s, character count = %s, %s has the most characters" %
        (len(tokens), sum(map(len, tokens)), reduce(lambda a, b: a if len(a) > len(b) else b, tokens))

list = ["cat,dog,fish", "turtle,charzard,pikachu,lame", "232.34,23.4,242.12%"]
for l in list:
    my_output(l)

试试这个。同时适用于Python2Python3

rows = [ "cat,dog,fish", "turtle,charzard,pikachu,lame", "232.34,23.4,242.12%" ]
for row in rows:
    tokens = row.split(',')
    token_cnt = len(tokens)
    char_cnt = sum([len(token) for token in tokens])
    longest_token = max(tokens, key=len)
    print("token count = %d, character count = %d, %s has the most characters" %(token_cnt, char_cnt, longest_token))

结果:

^{pr2}$

编辑:

现在使用max而不是我愚蠢的选择sort来寻找最长的单词,灵感来自@inspector4dget的答案。在

假设您有一个逗号分隔的行文件:

with open('path/to/input') as infile:
  for i,line in enumerate(infile, 1):
    toks = line.split(',')
    print "row %d: token_count=%d character_count=%d '%s' has the most characters" %(len(toks), sum(len(t) for t in toks), max(toks, key=len))

相关问题 更多 >