如何将两个for循环合并为列表理解

时间:2018-05-01 03:47:31

标签: python for-loop list-comprehension

由于我处理大量数据,如何将这两个for循环合并到列表解析中。此函数的目的是查找给定字符串中的大写单词数。给出的数据是电子邮件文本列表,这应该返回一个数字列表(数字是每个电子邮件主题中的大写字母数)。

def get_capital_prop(data):
    total_capitals = []
    temp = 0

    for i in range(len(data)):
        count = 0
        for word in data[i]:
            count += sum(1 for c in word if c.isupper())
        total_capitals.append(count / len(data[i]))
    return total_capitals

2 个答案:

答案 0 :(得分:1)

假设我正确理解你正在寻找以大写字母开头的单词数量,这里有一个简单的方法:

def get_capital_prop(data):
    return len([word for words in data for word in words if word[0].isupper()])

此解决方案假定每个单词至少有一个字母,并生成临时列表。稍微复杂的解决方案可以处理零长度的单词,并在不创建中间列表的情况下获得数字,但无论如何这都是一个很好的起点。

根据更新的说明,您真正想要的只是在字符串列表列表中获取所有大写字符的计数列表。那应该是这样的:

def get_capital_prop(data):
    return [len([c for c in email if c.isupper()]) for email in data]

或者,避免创建中间列表:

def get_capital_prop(data):
    return [sum(1 for c in email if c.isupper()) for email in data]

答案 1 :(得分:0)

根据您当前的实现,我假设您在包含大写字母的单词总数之后。

def is_caps(word):
    return word.isupper() and word.isalpha()

def get_capital_prop(data):
    return len([word for words in data for word in words if is_caps(word)])
如果字符串包含至少一个字母且每个字母都是大写,则

isupper()将返回True。这会忽略任何没有" upper"的数字,符号或特殊字符。或"降低"案件。辅助函数is_caps检查单词是否全部大写仅包含字母字符,如果是这种情况则返回True,否则返回False

以下是我所包含的一个简单示例:

在:

some_text = '''
This is just some EXAMPLE TEXT that
I have put together.  Hopefully this ANSWER
is helpfuL!! 123AA'''

rem = ',!?.\'"()'  # Symbol characters removed from the start and end of words
data = [[word.strip(rem) for word in words.split(' ')] for words in some_text.split('\n')]

输出:

>>>print(data)  # Only 4 fully capitalized words: EXAMPLE, TEXT, I and ANSWER
[[''], ['This', 'is', 'just', 'some', 'EXAMPLE', 'TEXT', 'that'], ['I', 'have', 'put', 'together', '', 'Hopefully', 'this', 'ANSWER'], ['is', 'helpfuL', '123AA']]

>>>print(get_capital_prop(data))
4

如果你想要包含撇号的大写单词,例如&#34; DON&#39; T&#34; &#34; SHOULDN&#39; T&#34; < / em>在你的回答中,你可以根据你的需要轻松改变is_caps()辅助函数中的逻辑。