从不同的索引位置遍历列表中的元素

2024-10-03 06:24:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这应该是一个简单的问题,但我还没有找到解决办法。 以下是练习:

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)

Tags: ofin元素supportforindexonelist
3条回答

我想这会满足你的要求:

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同时获取索引和单词的示例:

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)

相关问题 更多 >