【发布时间】:2020-10-21 14:07:06
【问题描述】:
我有一个函数modify如下:
list_with_chunks = [['hi','hello','how are you?'],['i','am','fine'],['what','about you?','.']]
flatten_list = ['hi','hello',...]
empty_list = []
# building the function to convert our sentences in list_with_chunks into another form:
def modify(sentence):
# do stuff here
# returning the result and appending them in empty_list
return empty_list.append(sentence*2)
我调用函数如下:
for i in flatten_list:
modify(i)
但是,我想直接从list_with_chunks 发送每个句子,而不是将其展平并将结果附加到empty_list。我该怎么做?
TIA。
【问题讨论】:
-
这里有什么帮助吗? @Barmar。谢谢。
-
您的问题并不完全清楚,但不妨试试
list(itertools.chain.from_iterable(map(map,itertools.repeat(modify),list_with_chunks)))。 -
@PaulPanzer 让我再试一次。我只是想将每个句子直接从
list_with_chunks发送到函数modify(sentence,top_n=5),而不是从flatten_list。我试过你的解决方案,我得到了这个结果:[None, None, None, None, None, None, None, None, None] -
那是因为无论输入什么,你的函数都会返回
None。你必须改变它而不是附加在函数中(无论如何我认为这是糟糕的设计),而是让它返回它的结果。另外,我不清楚您所说的句子是什么意思,句子是子列表还是单个字符?我发布的 sn-p 假定为后者。 -
这是一个简单的示例输入
list_with_chunks = [list(c) for c in "list of lists".split()]modify = str.upper。你可以用它来测试sn-p。
标签: python list split list-comprehension chunks