列表理解帮助:Python

2024-10-01 11:34:49 发布

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

我需要帮助使用python和列表理解查找给定定义的结果

firstSentence = ["Help", "me", "stack", "overflow", "you're", "my", "only", "hope"]
secondSentence = ["I", "hope", "you're", "enjoying", "the", "riddles", "I've", "created"]

应该打印什么:['HelpI', 'Helpthe', 'meI', 'stackI', 'stackhope', 'stackthe', "stackI've", 'overflowI', 'overflowhope', "overflowyou're", 'overflowthe', 'overflowriddles', "overflowI've", 'overflowcreated', "you'reI", "you'rehope", "you'rethe", "you'reI've", 'myI', 'onlyI', 'onlythe', 'hopeI', 'hopethe']

我知道这句话和小于第二句的组合有关,但我不确定如何执行

使用列表理解:鉴于第一句和第二句的长度不能超过第二句,我如何组合第一句和第二句


Tags: reyou列表定义stackmyvehelp
1条回答
网友
1楼 · 发布于 2024-10-01 11:34:49

要获得列表理解的清晰抓取,首先让我们尝试使用嵌套循环获得所需的输出:

firstSentence = ["Help", "me", "stack", "overflow", "you're", "my", "only", "hope"]
secondSentence = ["I", "hope", "you're", "enjoying", "the", "riddles", "I've", "created"]

result = []
for firstWord in firstSentence:
    for secondWord in secondSentence:
        if len(secondWord) < len(firstWord):
            result.append(firstWord+secondWord)
print(result)

输出:

['HelpI', 'Helpthe', 'meI', 'stackI', 'stackhope', 'stackthe', "stackI've", 'overflowI', 'overflowhope', "overflowyou're", 'overflowthe', 'overflowriddles', "overflowI've", 'overflowcreated', "you'reI", "you'rehope", "you'rethe", "you'reI've", 'myI', 'onlyI', 'onlythe', 'hopeI', 'hopethe']

现在,让我们使用列表理解转换此嵌套循环:

result = [firstWord+secondWord for firstWord in firstSentence for secondWord in secondSentence if len(secondWord) < len(firstWord)]
print(result)

输出:

['HelpI', 'Helpthe', 'meI', 'stackI', 'stackhope', 'stackthe', "stackI've", 'overflowI', 'overflowhope', "overflowyou're", 'overflowthe', 'overflowriddles', "overflowI've", 'overflowcreated', "you'reI", "you'rehope", "you'rethe", "you'reI've", 'myI', 'onlyI', 'onlythe', 'hopeI', 'hopethe']

注意:在Python中,变量未声明或用作camelCase。它更喜欢小写变量名,其中的单词由下划线(_)分隔

根据Python PEP-8指南:

Function names should be lowercase, with words separated by underscores as necessary to improve readability. Variable names follow the same convention as function names.

参考:

相关问题 更多 >