使用带星号的表达式和变量
Using starred expressions with variables
我打算删除单词列表中由 "-"
链接的单词。
我会使用 starred expression 因为我忽略了我是否会在 split()
.
列表中获得一个列表
我用常量表达式工作得很好:
[i for i in [*['1','2'],'1']]
产量:
['1', '2', '1']
我将使用变量获得相同的过程:
test=pd.DataFrame( {'columns0' :[['hanging', 'heart', 't-light', 'holder']]})
test.apply(lambda x : [e if len(e.split('-'))==1 else (*e.split('-')) for e in x ])
但如您所料,它不起作用:
File "<ipython-input-1109-dda6b3df14bb>", line 3
test.apply(lambda x : [e if len(e.split('-'))==1 else ( *e.split('-')) for e in x ])
^
SyntaxError: can't use starred expression here
为什么还要费心区分这些情况? split
returns 列表无论长度如何。只是嵌套理解:
lambda x: [token for e in x for token in e.split('-')]
显然,答案是列表理解不支持拼音。
PEP 总结摘要说:"This PEP does not include unpacking operators inside list, set and dictionary comprehensions although this has not been ruled out for future proposals."
来源:https://www.python.org/dev/peps/pep-0448/#id6
在对类似问题的回答中,@Curtis Lustmore 解释说:"The assignment operator (and all variations on it) forms a statement in Python, not an expression. Unfortunately, list comprehensions (and other comprehensions, like set, dictionary and generators) only support expressions"
来源:
我打算删除单词列表中由 "-"
链接的单词。
我会使用 starred expression 因为我忽略了我是否会在 split()
.
我用常量表达式工作得很好:
[i for i in [*['1','2'],'1']]
产量:
['1', '2', '1']
我将使用变量获得相同的过程:
test=pd.DataFrame( {'columns0' :[['hanging', 'heart', 't-light', 'holder']]})
test.apply(lambda x : [e if len(e.split('-'))==1 else (*e.split('-')) for e in x ])
但如您所料,它不起作用:
File "<ipython-input-1109-dda6b3df14bb>", line 3
test.apply(lambda x : [e if len(e.split('-'))==1 else ( *e.split('-')) for e in x ])
^
SyntaxError: can't use starred expression here
为什么还要费心区分这些情况? split
returns 列表无论长度如何。只是嵌套理解:
lambda x: [token for e in x for token in e.split('-')]
显然,答案是列表理解不支持拼音。
PEP 总结摘要说:"This PEP does not include unpacking operators inside list, set and dictionary comprehensions although this has not been ruled out for future proposals."
来源:https://www.python.org/dev/peps/pep-0448/#id6
在对类似问题的回答中,@Curtis Lustmore 解释说:"The assignment operator (and all variations on it) forms a statement in Python, not an expression. Unfortunately, list comprehensions (and other comprehensions, like set, dictionary and generators) only support expressions"
来源: