【问题标题】:Iterating through elements in a list from different index positions从不同的索引位置遍历列表中的元素
【发布时间】:2021-12-09 04:15:30
【问题描述】:

这应该很容易,但我根本没有找到解决方案。 这是练习:

从“舒适”、“圆形”、“支撑”、“机械”这 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)

【问题讨论】:

  • for i in words[1:]:
  • 另外,你的函数没有return
  • 您在寻找组合还是排列?下面的一些解决方案为您提供了排列,其中 ('round, ','support, ') 和 (support, ','round, ') 都作为两个不同的东西输出。组合只会输出其中一个。

标签: python list for-loop indexing


【解决方案1】:

我认为这会满足您的需求:

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 有点陌生,我想知道你是否能告诉我你的代码中的这一行是做什么的?我不明白是将元素添加到空列表中,但我不确定 f' 代表什么:combinations.append(f'{first_word}, {second_word}')
  • @DianaGalindo 绝对! “f”代表format string or "f-string"。这是一种将字符串与变量连接起来的干净、易读的方法。在引号前放置 f 时,它允许您在花括号之间放置变量或表达式,然后只需在其之间或周围键入额外的字符。我在这种情况下使用了它,因此您不需要在输入列表中包含逗号和空格。相反,我使用 f-string 的方式添加了逗号和空格,同时将新组合添加到您的列表中。
  • @DianaGalindo 顺便说一句,有很多方法可以格式化您的字符串。使用的旧方法是.format()'My name is {}'.format('Kyle') 这是一个不错的解决方案,但不那么可读。您还可以使用 + 运算符连接您的字符串。 AFAIK,在大多数编程语言中使用最广泛的格式是某种形式的 f 字符串,所以它们是一个使用的好习惯。
  • 你好@KyleDixon,谢谢你的解释。我以前见过 .format(),但我不知道它已更新为 f'。这是完全有道理的。感谢您也链接到“f-string”的资源页面!
【解决方案2】:

如果您想在这样的 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,它返回从第二个元素开始的列表。

【讨论】:

    【解决方案3】:

    你也可以像这样使用itertools.permutations()

    from itertools import permutations
    
    lst = ['comfortable', 'round', 'support', 'machinery']
    
    for i in list(permutations(lst, 2)):
        print(i)
    

    【讨论】:

    • 您好!感谢您提供此解决方案。它帮助我了解了组合和排列(以及它们在 Python 中的方法)之间的区别。
    • 不客气
    猜你喜欢
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多