Python - 列表理解如何一次插入 2 个元素?

Python - List comprehension how to insert 2 elements at a time?

我在 python 中有一个 pluralize 函数,它打印单词的复数形式

pluralize("wolf") = wolves

例如,在我的 input_list

input_list = ["wolf","dog","cat","cow","pig"]

我可以做这个简单的列表理解来填充复数形式

output_list = [pluralize(data) for data in input_list]

给予["wolves","dogs","cats.....]

不过我需要

["wolves","wolf","dogs","dog","cats","cat","cows","cow"....]

我怎样才能得到这个通过理解生成的列表?

我的意思是

output_list = [pluralize(data),data for data in input_list]

(显然行不通)

您可以添加另一个循环:

[word for data in input_list for word in (pluralize(data), data)]

演示:

>>> plural_forms = {'wolf': 'wolves', 'dog': 'dogs', 'cat': 'cats', 'cow': 'cows', 'pig': 'pigs'}
>>> pluralize = plural_forms.get
>>> input_list = ["wolf","dog","cat","cow","pig"]
>>> [word for data in input_list for word in (pluralize(data), data)]
['wolves', 'wolf', 'dogs', 'dog', 'cats', 'cat', 'cows', 'cow', 'pigs', 'pig']
sum([[x, plural(x)] for x in data], [])

同样:

>>> sum([[x, x.upper()] for x in "hello"], [])
['h', 'H', 'e', 'E', 'l', 'L', 'l', 'L', 'o', 'O']

希望对您有所帮助,

output_list = [item for sublist in [[pluralize(data),data] for data in input_list]for item in sublist]

最佳,