简体   繁体   English

如何在 Python 的 for 循环中更改列表元素的位置

[英]How to change list elements positions in a for loop in Python

I'm fairly new to programming and I'm really stuck in a problem.我对编程还很陌生,我真的陷入了一个问题。

Say I have the following list:假设我有以下列表:

a = [2, "**", 2, "@"]

The list might contain more elements.该列表可能包含更多元素。

What I need to do is change positions between "**" and "@", so I would have我需要做的是改变“**”和“@”之间的位置,所以我会有

a = [2, "@", 2, "**"]

I've been trying to do it with a for loop, using element indexes to perform the change, but the list index is getting out of range.我一直在尝试使用 for 循环,使用元素索引来执行更改,但列表索引超出范围。

How could I do it?我怎么能做到?

Here's my code:这是我的代码:

for j in range (len(expression)):
    if expression[j] == "**":
        if expression[j+2] == "@":
            expression[j], expression[j+2] = expression[j+2], expression[j]
print(expression)

My comment in an answer (altho pretty simple tbf)我在答案中的评论(虽然很简单 tbf)

>>> expression = [2, "**", 2, "@", "**"]
>>> for j in range (len(expression)):
...     if expression[j] == "**":
...         if (
...             len(expression) > j +2 
...             and expression[j+2] == "@"
...         ):
...             expression[j], expression[j+2] = expression[j+2], expression[j]
... 
>>> print(expression)
[2, '@', 2, '**', '**']

Explanation : if the current value is ** you are attempting to access j+2 .说明:如果当前值为**您正在尝试访问j+2 However, your list might not have that index (for example what if ** is the last element?).但是,您的列表可能没有该索引(例如,如果**是最后一个元素呢?)。 To cater for this case I extend your if statement to first check for length and then check for j+2 values.为了适应这种情况,我将您的if语句扩展为首先检查长度,然后检查j+2值。 If/when the first check/condition fails, the second condition is skipped (not checked) and thus the IndexError does not happen.如果/当第一个检查/条件失败时,将跳过(未检查)第二个条件,因此不会发生 IndexError。

(updated the input list to show that even ** at the end of the list wont raise an error) (更新了输入列表以显示即使列表末尾的**不会引发错误)

Try the below试试下面的

# assuming "**" and "@" apper once in the list
a = [2, "**", 2, "@"]
idx_1 = a.index("**")
idx_2 = a.index("@")
# I need to change if and only if ** and @ are separated by another element
if abs(idx_1 - idx_2) > 1:
  del a[idx_1]
  a.insert(idx_1,"@")
  del a[idx_2]  
  a.insert(idx_2,"**")
print(a)

I thought about just getting the positions out of the list and then swapping them.我想过从列表中取出职位,然后交换它们。

for idx , j in enumerate(a):
    if (j == "**"):
        pos1 = idx
    elif (j=="@"):
        pos2 = idx
    
a[pos1],a[pos2] = a[pos2],a[pos1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM