Python 中的 for 循环交换效果不太好

问题描述 投票:0回答:1

如何只交换 2 个项目并转到另外 2 个项目而不交换我已经交换过的项目? 这是 Codeforces 网站上的问题:https://codeforces.com/problemset?order=BY_RATING_ASC&tags=shortest+paths

我尝试过:

item1, item2 = item2, item1

但它不适用于我只访问的两个项目。它运行所有列表!

这是我的代码:

# If you find 'G' after 'B' swap them and go through the loop without accessing the last items. 
queue_time = list(map(int, input().split()))
queue = queue_time[0]
time = queue_time[-1]
persons = ["B", "G", "G"]

while time > 0:
  for i in range(len(persons)-1):
    if persons[i] == "B" and persons[i + 1] == "G":
      persons[i], persons[i +1] = persons[i +1], persons[i]
    if persons[i + 1]:
      continue
  time -= 1
print(persons)
python for-loop swap
1个回答
0
投票

正如 John Gorden 上面所说,你可以在每次迭代中将 for 循环前进两个位置(而不是 1)

>>> persons = ["B", "G", "G"]
>>> for i in range(0, len(persons), 2):
    persons[i:i+2] = reversed(persons[i:i+2])

    
>>> print(persons)
['G', 'B', 'G']
© www.soinside.com 2019 - 2024. All rights reserved.