【问题标题】:How to feed a function one value at a time from a list of lists?如何从列表列表中一次为函数提​​供一个值?
【发布时间】: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


【解决方案1】:

通过 list_with_chunks 使用嵌套循环。

for i in range(len(list_with_chunks)):
    for j in range(len(list_with_chunks[i])):
        modify(list_with_chunks[i][j], top_n=5)

【讨论】:

  • 这给了我一个 TypeError。 python --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-24-f2fb08579ef7> in <module>() ----> 1 for i in len(list_with_chunks): 2 for j in len(list_with_chunks[i]): 3 modify(list_with_chunks[i][j], top_n=5) TypeError: 'int' object is not iterable 请记住 list_with_chunks 包含 strings 作为其值。
  • 不,不是。它是列表列表:[['a','b','c'],['d','e','f']] 这样。
  • 您能否显示从 list_with_chunks 启动到该错误的代码。
  • list_with_chunks = [['hi','hello','how are you?'],['i','am','fine'],['what','about you?','.']] new_list = [] def modify(sentence): return new_list.append(sentence*2) for i in len(list_with_chunks): for j in len(list_with_chunks[i]): modify(list_with_chunks[i][j])
【解决方案2】:

我完全不明白这个问题!但这是你要找的吗:

for x in list_with_chunks:
    for y in x:
        modify(y)

您只需要再次迭代列表中的每个元素,以便将它们添加到空列表中。

【讨论】:

    猜你喜欢
    • 2022-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-01
    • 2021-09-29
    • 2021-02-16
    • 2016-12-09
    • 1970-01-01
    相关资源
    最近更新 更多