简体   繁体   English

没有 if 但有 else 的列表理解

[英]list comprehension without if but with else

My question aims to use the else condition of a for-loop in a list comprehension.我的问题旨在在列表理解中使用 for 循环的 else 条件。

example:例子:

empty_list = []
def example_func(text):
    for a in text.split():
        for b in a.split(","):
            empty_list.append(b)
        else:
            empty_list.append(" ")

I would like to make it cleaner by using a list comprehension with both for-loops.我想通过对两个 for 循环使用列表理解来使其更清晰。

But how can I do this by including an escape-clause for one of the loops (in this case the 2nd).但是我如何通过为其中一个循环(在本例中为第二个)包含一个转义子句来做到这一点。 I know I can use if with and without else in a list comprehension.我知道我可以在列表理解中使用 if 和 else 。 But how about using else without an if statement.但是如何在没有 if 语句的情况下使用 else。

Is there a way, so the interpreter will understand it as escape-clause of a for loop?有没有办法让解释器将其理解为 for 循环的转义子句?

Any help is much appreciated!任何帮助深表感谢!

EDIT: Thanks for the answers!编辑:感谢您的回答! In fact im trying to translate morse code.事实上,我正在尝试翻译莫尔斯电码。

The input is a string, containing morse codes.输入是一个字符串,包含摩尔斯电码。 Each word is separated by 3 spaces.每个单词由 3 个空格分隔。 Each letter of each word is separated by 1 space.每个单词的每个字母由 1 个空格分隔。

def decoder(code): 
    str_list = [] 
    for i in code.split("   "): 
        for e in i.split(): 
            str_list.append(morse_code_dic[e]) 
        else: 
            str_list.append(" ") 
     return "".join(str_list[:-1]).capitalize()

print(decoder(".. -   .-- .- ...   .-   --. --- --- -..   -.. .- -.--"))

I want to break down the whole sentence into words, then translate each word.我想把整个句子分解成单词,然后翻译每个单词。 After the inner loop (translation of one word) is finished, it will launch its escape-clause else, adding a space, so that the structure of the whole sentence will be preserved.内循环(一个词的翻译)完成后,它会启动它的escape-clause else,添加一个空格,这样整个句子的结构就会被保留下来。 That way, the 3 Spaces will be translated to one space.这样,3 个空格将被转换为一个空格。

As noted in comments, that else does not really make all that much sense, since the purpose of an else after a for loop is actually to hold code for conditional execution if the loop terminates normally (ie not via break ), which your loop always does, thus it is always executed.正如评论中指出的那样, else并没有多大意义,因为在for循环之后else的目的实际上是在循环正常终止(即不是通过break )时保存用于条件执行的代码,你的循环总是,因此它总是被执行。

So this is not really an answer to the question how to do that in a list comprehension, but more of an alternative.所以这并不是如何在列表理解中做到这一点的问题的真正答案,而是更多的替代方案。 Instead of adding spaces after all words, then removing the last space and joining everything together, you could just use two nested join generator expressions, one for the sentence and one for the words:您可以只使用两个嵌套的join生成器表达式,一个用于句子,一个用于单词,而不是在所有单词后添加空格,然后删除最后一个空格并将所有内容连接在一起:

def decoder(code): 
    return " ".join("".join(morse_code_dic[e] for e in i.split())
                    for i in code.split("   ")).capitalize()

As mentioned in the comments, the else clause in your particular example is pointless because it always runs.如评论中所述,您的特定示例中的else子句毫无意义,因为它始终运行。 Let's contrive an example that would let us investigate the possibility of simulating a break and else .让我们设计一个示例,让我们研究模拟breakelse的可能性。

Take the following string:取以下字符串:

s = 'a,b,c b,c,d c,d,e, d,e,f'

Let's say you wanted to split the string by spaces and commas as before, but you only wanted to preserve the elements of the inner split up to the first occurrence of c :假设您想像以前一样用空格和逗号分割字符串,但您只想保留内部分割的元素,直到第一次出现c

out = []
for i in s.split(): 
    for e in i.split(','):
        if e == 'c':
            break
        out.append(e)
    else: 
        out.append('-')

The break can be simulated using the arcane two-arg form of iter , which accepts a callable and a termination value:可以使用iter的神秘双参数形式模拟break ,它接受一个可调用值和一个终止值:

>>> x = list('abcd')
>>> list(iter(iter(x).__next__, 'c'))
['a', 'b']

You can implement the else by chaining the inner iterable with ['-'] .您可以通过使用['-'] 链接内部可迭代对象来实现else

>>> from itertools import chain
>>> x = list('abcd')
>>> list(iter(chain(x, ['-'])
.__next__, 'c'))
['a', 'b']
>>> y = list('def')
>>> list(iter(chain(y, ['-'])
.__next__, 'c'))
['d', 'e', 'f', '-']

Notice that the placement of chain is crucial here.请注意, chain的放置在这里至关重要。 If you were to chain the dash to the outer iterator, it would always be appended, not only when c is not encountered:如果您要将破折号链接到外部迭代器,它将始终被附加,而不仅仅是在未遇到c时:

>>> list(chain(iter(iter(x).__next__, 'c'), ['-']))
['a', 'b', '-']

You can now simulate the entire nested loop with a single expression:您现在可以使用单个表达式模拟整个嵌套循环:

from itertools import chain

out = [e for i in s.split() for e in iter(chain(i.split(','), ['-']).__next__, 'c')]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM