我有一个任务需要对列表的每个元素进行操作,操作的结果取决于列表中的其他元素.
例如,我可能希望以特定字符开头连接条件列表:
此代码解决了以下问题:
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)
您可以使用正则表达式来简洁地完成此操作.然而,这确实绕过了关于如何操作依赖列表元素的问题.致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.00456210269896和0.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跟随我们的两个.
这个怎么样:
>>> 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)