这应该是一个简单的问题,但我还没有找到解决办法。 以下是练习:
Start with 4 words “comfortable”, “round”, “support”, “machinery”, return a list of all possible 2 word combinations.
Example:["comfortable round", "comfortable support", "comfortable machinery", ...]
我已经开始编写一个循环,它将遍历每个元素,从索引[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”)开始迭代。我尝试过操作索引(索引[0]+1),但它当然不会返回任何内容,因为元素是字符串。 我知道需要进行从字符串到索引的转换,但我不确定如何进行
我也尝试过定义一个函数,但它不会返回任何函数
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)
我想这会满足你的要求:
说明:
您需要在函数末尾包含一个return语句来返回值。在我的示例函数
word_variations()
中,我首先定义一个名为combinations
的空列表。这将存储我们计算的每个组合。然后我遍历输入word_list
中的所有单词,创建另一个内部循环以再次遍历所有单词,如果first_word
不等于second_word
,则将组合附加到我的combinations
列表中。完成所有循环后,从函数返回完成的列表如果我稍微更改代码以在新行上打印每个结果:
输出为:
如果您想在Python循环中使用这样的索引,那么应该使用^{} 或遍历列表的长度。以下示例将从第二个元素开始循环
使用
enumerate
同时获取索引和单词的示例:仅使用索引的示例:
注意:
set_of_words[1:]
上面是一个slice返回从第二个元素开始的列表您也可以像这样使用
itertools.permutations()
相关问题 更多 >
编程相关推荐