简体   繁体   English

扩展列表中的元素

[英]Expanding elements in a list

I'm looking for a "nice" way to process a list where some elements need to be expanded into more elements (only once, no expansion on the results). 我正在寻找一种处理列表的“不错”的方法,其中某些元素需要扩展为更多元素(仅一次,结果不扩展)。

Standard iterative way would be to do: 标准的迭代方式是:

i=0
while i < len(l):
   if needs_expanding(l[i]):
      new_is = expand(l[i])
      l[i:i] = new_is
      i += len(new_is)
   else:
      i += 1

which is pretty ugly. 这很丑。 I could rewrite the contents into a new list with: 我可以使用以下方法将内容重写为新列表:

nl = []
for x in l:
   if needs_expanding(x):
      nl += expand(x)
   else:
      nl.append(x)

But they both seem too long. 但是他们似乎都太长了。 Or I could simply do 2 passes and flatten the list later: 或者我可以简单地进行2次传递,然后将列表展平:

flatten(expand(x) if needs_expanding(x) else x for x in l)
# or
def try_expanding(x)....
flatten(try_expanding(x) for x in l)

but this doesn't feel "right" either. 但这也不是“正确的”。

Are there any other clear ways of doing this? 还有其他明确的方法吗?

Your last two answers are what I would do. 您的最后两个答案是我会做的。 I'm not familiar with flatten() though, but if you have such a function then that looks ideal. 虽然我对flatten()并不熟悉,但是如果您有这样的功能,那看起来很理想。 You can also use the built-in sum() : 您也可以使用内置的sum()

sum(expand(x) if needs_expanding(x) else [x] for x in l, [])
sum(needs_expanding(x) and expand(x) or [x] for x in l, [])

The last one is probably your most pythonic, but you could try an implied loop (or in py3, generator) with map: 最后一个可能是您最喜欢的Python语言,但是您可以尝试使用map进行隐式循环(或在py3中,生成器中):

flatten(map(lambda x: expand(x) if needs_expanding(x) else x, l))
flatten(map(try_expanding, l))

If you do not need random access in the list you are generating, you could also use write a generator. 如果不需要在生成的列表中进行随机访问,则也可以使用编写生成器。

def iter_new_list(old_list):    
    for x in old_list:
       if needs_expanding(x):
           for y in expand(x):
               yield y
       else:
           yield x

new_list = list(iter_new_list(old_list))

This is functionally equivalent to your second example, but it might be more readable in your real-world situation. 这在功能上等效于您的第二个示例,但是在您的实际情况下可能更易读。

Also, Python coding standards forbid the use of lowercase-L as a variable name, as it is nearly indistinguishable from the numeral one. 而且,Python编码标准禁止使用小写字母L作为变量名,因为它与数字几乎没有区别。

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

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