我在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]
(显然不起作用)
答案 0 :(得分:3)
你可以添加另一个循环:
[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']
答案 1 :(得分:2)
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']
答案 2 :(得分:0)
我希望这有助于,
output_list = [item for sublist in [[pluralize(data),data] for data in input_list]for item in sublist]
最佳,