从根词

时间:2015-06-12 15:47:33

标签: python

我需要在Python中编写一个函数,它接受一个根词并通过向根词添加一个单词列表来生成一个列表。即Input = juicy, list =apple,tomato, orange , Output = juicy apple, juicy tomato, juicy orange.建议

def generate('word') 
  list  = ['a' ,' b', 'c', 'd']

...

 new list = [ 'word a', 'word b', 'word c', 'word d']

3 个答案:

答案 0 :(得分:2)

该功能将是:

def generate(root, words):
    return [root + ' ' + w for w in words]

另一个解决方案是使用lambda表达式:

generate = lambda root, words: [root + ' ' + w for w in words]

在这两种情况下:

>>> generate('juicy', ['apple', 'tomato', 'orange'])
['juicy apple', 'juicy tomato', 'juicy orange']

答案 1 :(得分:0)

这是基本的字符串格式化+列表理解

>>> root_word = 'juicy'
>>> my_list = ['a', 'b', 'c', 'd']
>>> new_list = ['{} {}'.format(root_word, i) for i in my_list]
>>> print new_list
['juicy a', 'juicy b', 'juicy c', 'juicy d']

这类似于以下内容:

>>> new_list = []
>>> for word in my_list:
...     new_word = '{} {}'.format(root_word, word)
...     # '{}' is a generic character to be formatted
...     # which in this case replaces root_word with the 
...     # first instance of '{}' and word with the second.
...     
...     my_list.append(word)
... print new_list
['juicy a', 'juicy b', 'juicy c', 'juicy d']

如果要在函数中添加它,只需定义:

def join_words(root_word, my_list):
    return ['{} {}'.format(root_word, i) for i in my_list]

你可能应该在函数中使用根词和列表BOTH作为参数,因为这会为你推广生成的代码:你可以将列表传递给函数并根据需要生成不同的组合单词。

答案 2 :(得分:0)

这是进行列表理解的另一种方法

def generate(word):
  list  = ['a' ,' b', 'c', 'd']
  return [word + ' ' + letter for letter in list]


print generate('word')