这应该是一个简单的问题,但我根本没有找到解决方案。下面是练习:
从4个单词"comfortable","round","support","machinery"开始,返回所有可能的2个单词组合的列表。
示例:["comfortable round", "comfortable support", "comfortable machinery", ...]
我已经开始编写一个循环,将通过每个元素,从元素在index[0]
:
words = ["comfortable, ", 'round, ', 'support, ', 'machinery, ']
index_zero= words[0]
for i in words:
words = index_zero + i
words_one = index_one + i
print(words)
>>> Output=
comfortable, comfortable,
comfortable, round,
comfortable, support,
comfortable, machinery
问题是当我想从第二个元素('round')开始迭代时。我已经尝试操作索引(index[0] + 1
),但当然,它不会返回任何元素是字符串。我知道需要进行从字符串到索引的转换,但我不确定如何进行。
我也尝试定义一个函数,但它将返回None
word_list = ["comfortable, ", 'round, ', 'support, ', 'machinery, ']
index_change = word_list[0]+ 1
def word_variations(set_of_words):
for i in set_of_words:
set_of_words = set_of_words[0] + i
set_of_words = word_variations(word_list)
print(set_of_words)
我认为这将做你正在寻找的:
def word_variations(word_list):
combinations = []
for first_word in word_list:
for second_word in word_list:
if first_word != second_word:
combinations.append(f'{first_word}, {second_word}')
return combinations
word_list = ["comfortable", "round", "support", "machinery"]
print(word_variations(word_list))
解释:
您需要在函数末尾包含return语句以返回值。在我的示例函数word_variations()
中,我首先定义一个名为combinations
的空列表。这将存储我们计算的每个组合。然后我遍历输入word_list
中的所有单词,创建另一个内部循环再次遍历所有单词,如果first_word
不等于second_word
,则将组合追加到combinations
列表。一旦所有循环完成,从函数返回完成的列表。
如果我稍微改变一下代码,将每个结果打印在新行上:
def word_variations(word_list):
combinations = []
for first_word in word_list:
for second_word in word_list:
if first_word != second_word:
combinations.append(f'{first_word}, {second_word}')
return combinations
word_list = ["comfortable", "round", "support", "machinery"]
for combo in word_variations(word_list):
print(combo)
输出为:
comfortable, round
comfortable, support
comfortable, machinery
round, comfortable
round, support
round, machinery
support, comfortable
support, round
support, machinery
machinery, comfortable
machinery, round
machinery, support
如果您想在这样的Python循环中使用索引,则应该使用enumerate
或遍历列表的长度。下面的示例将在第二个元素处开始循环。
使用enumerate
:
for i, word in enumerate(set_of_words[1:]):
仅使用索引的示例:
for i in range(1, len(set_of_words)):
注意:上面的set_of_words[1:]
是一个slice,返回从第二个元素开始的列表。
您也可以像这样使用itertools.permutations()
from itertools import permutations
lst = ['comfortable', 'round', 'support', 'machinery']
for i in list(permutations(lst, 2)):
print(i)