当输出依赖于其他元素时,以pythonic方式在列表上操作

Lon*_*Rob 12 python

我有一个任务需要对列表的每个元素进行操作,操作的结果取决于列表中的其他元素.

例如,我可能希望以特定字符开头连接条件列表:

此代码解决了以下问题:

x = ['*a', 'b', 'c', '*d', 'e', '*f', '*g']
concat = []
for element in x:
    if element.startswith('*'):
        concat.append(element)
    else:
        concat[len(concat) - 1] += element
Run Code Online (Sandbox Code Playgroud)

导致:

concat
Out[16]: ['*abc', '*de', '*f', '*g']
Run Code Online (Sandbox Code Playgroud)

但这似乎非常恐怖.list当操作结果取决于先前的结果时,如何对a的元素进行操作?

che*_*ner 13

一些相关的摘录import this(什么是Pythonic的仲裁者):

  • 简单比复杂更好
  • 可读性很重要
  • 显式优于隐式.

我会使用这样的代码,而不用担心用"flatter"替换for循环.

x = ['*a', 'b', 'c', '*d', 'e', '*f', '*g']
partials = []
for element in x:
    if element.startswith('*'):
        partials.append([])
    partials[-1].append(element)
concat = map("".join, partials)
Run Code Online (Sandbox Code Playgroud)

  • 可爱.+1将讨论带回"*pythonic*"并远离整洁/紧凑/快速. (4认同)

mir*_*ulo 7

您可以使用正则表达式来简洁地完成此操作.然而,这确实绕过了关于如何操作依赖列表元素的问题.致mbomb007以改善允许的角色功能.

import re
z = re.findall('\*[^*]+',"".join(x))
Run Code Online (Sandbox Code Playgroud)

输出:

['*abc', '*de', '*f', '*g']
Run Code Online (Sandbox Code Playgroud)

小基准:

大金刚的回答:

import timeit
setup = '''
import re
x = ['*a', 'b', 'c', '*d', 'e', '*f', '*g']
y = ['*a', 'b', 'c', '*d', 'e', '*f', '*g'] * 100
'''
print (min(timeit.Timer('re.findall("\*[^\*]+","".join(x))', setup=setup).repeat(7, 1000)))
print (min(timeit.Timer('re.findall("\*[^\*]+","".join(y))', setup=setup).repeat(7, 1000)))
Run Code Online (Sandbox Code Playgroud)

返回0.00226416693456,并0.06827958075分别.

切普纳的回答:

setup = '''
x = ['*a', 'b', 'c', '*d', 'e', '*f', '*g']
y = ['*a', 'b', 'c', '*d', 'e', '*f', '*g'] * 100
def chepner(x):
    partials = []
    for element in x:
        if element.startswith('*'):
            partials.append([])
        partials[-1].append(element)
    concat = map("".join, partials)  
    return concat
'''
print (min(timeit.Timer('chepner(x)', setup=setup).repeat(7, 1000)))
print (min(timeit.Timer('chepner(y)', setup=setup).repeat(7, 1000)))
Run Code Online (Sandbox Code Playgroud)

返回0.004562102698960.364635824689分别.

萨克瑟姆的回答

setup = '''
x = ['*a', 'b', 'c', '*d', 'e', '*f', '*g'] 
y = ['*a', 'b', 'c', '*d', 'e', '*f', '*g'] * 100

'''
print (min(timeit.Timer("['*'+item for item in ''.join(x).split('*') if item]", setup=setup).repeat(7, 1000)))
print (min(timeit.Timer("['*'+item for item in ''.join(y).split('*') if item]", setup=setup).repeat(7, 1000))))
Run Code Online (Sandbox Code Playgroud)

返回0.00104848906006,并0.0556093171512分别.

ts ; Saksham 博士比我的快一点,然后Chepner跟随我们的两个.


Sak*_*rma 6

这个怎么样:

>>> x = ['*a', 'b', 'c', '*d', 'e', '*f', '*g']
>>> print ['*'+item for item in ''.join(x).split('*') if item]
['*abc', '*de', '*f', '*g']
Run Code Online (Sandbox Code Playgroud)

  • Pythonic!=简洁 (2认同)