這應該很容易,但我還沒有找到解決方案。這是練習:
以“comfortable”、“round”、“support”、“machinery” 4 個詞開頭,回傳所有可能的 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)
uj5u.com熱心網友回復:
我認為這可以滿足您的要求:
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. 這將存盤我們計算的每個組合。然后我遍歷 input 中的所有單詞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
uj5u.com熱心網友回復:
如果你想在這樣的 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:]上面是一個切片,它回傳從第二個元素開始的串列。
uj5u.com熱心網友回復:
你也可以itertools.permutations()這樣使用
from itertools import permutations
lst = ['comfortable', 'round', 'support', 'machinery']
for i in list(permutations(lst, 2)):
print(i)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/335417.html
