简体   繁体   English

for 循环,lst[i] = lst[i - 1] - Python

[英]for loop, lst[i] = lst[i - 1] - Python

Why doesn't this work?为什么这不起作用?

def func(lst):
    for i in range(len(lst)):
        lst[i] = lst[i - 1]
    return lst


print(func([1, 2, 3, 4]))

Expected output: [4, 1, 2, 3]预期 output: [4, 1, 2, 3]
Actual output: [4, 4, 4, 4]实际 output: [4, 4, 4, 4]

why python assign lst[1] = lst[-1] when it should be lst[1] = lst[0]为什么 python 分配 lst[1] = lst[-1] 而应该是 lst[1] = lst[0]

The following works.以下作品。 lst[i] was reset in the for loop. lst[i] 在 for 循环中被重置。


def func(lst):
    output = []
    for i in range(len(lst)):
        output.append(lst[i - 1])
    return output


print(func([1, 2, 3, 4]))

You got a logic error here, at first iteration you doing smth like lst[0] = lst[-1] and then pulling this value to all remaining indeces.您在这里遇到了一个逻辑错误,在第一次迭代时,您像 lst[0] = lst[-1] 那样做某事,然后将该值拉到所有剩余的索引中。 If you want to shift array left one pos try something like this:如果您想将数组左移一位,请尝试以下操作:

def shifter(lst):
    return lst[-1:] + lst[:-1]

Lists are mutable objects and you are iterating over a single list.列表是可变对象,您正在迭代单个列表。 On each iteration, the variable lst is pointing to the current state of the list, and inside your loop you are modifying that current state.在每次迭代中,变量lst都指向列表的当前 state,并且在您的循环中,您正在修改当前的 state。

Your expected answer would require that Python would copy and remember the initial state of the list at the beginning of the loop, which Python does not do.您的预期答案将要求 Python 复制并记住循环开始时列表的初始 state,而 Python 不会这样做。

def func(lst):
    initial = lst[:]  # copy lst
    for i in range(len(lst)):
        lst[i] = initial[i - 1]
    return lst


print(func([1, 2, 3, 4]))
def func(lst):
for i in range(len(lst)):
    print(i, lst[i-1])
    lst[i] = lst[i - 1]
return lst

If you look at how your code executes, the first iteration, i will be 0, and lst[i-1] will be lst[-1] which points to the last element in the array (4).如果你看看你的代码是如何执行的,第一次迭代,i 将是 0,lst[i-1] 将是 lst[-1],它指向数组 (4) 中的最后一个元素。 So after first iteration, your array looks likes this: [4,2,3,4] In the second, i=1, and lst[i-1] will be lst[0] which has a value a 4 now: So now lst[1] will be 4, [4,4,3.4] And so on.... Hope that helps.所以在第一次迭代之后,你的数组看起来像这样:[4,2,3,4] 在第二个中,i=1,lst[i-1] 将是 lst[0],现在的值为 4:所以现在 lst[1] 将是 4, [4,4,3.4] 等等....希望有帮助。

You can insert the last item at the first index and delete the last item afterwards:您可以在第一个索引处插入最后一项,然后删除最后一项:

def func(lst):
    lst[:0] = lst[-1:]
    del lst[-1:]
    return lst

so that func([1, 2, 3, 4]) returns: [4, 1, 2, 3]这样func([1, 2, 3, 4])返回: [4, 1, 2, 3]

Step through your code, one line at a time:单步执行您的代码,一次一行:

Initially, lst is [1, 2, 3, 4] , so len(lst) is 4 .最初, lst[1, 2, 3, 4] ,所以len(lst)4 range(n) returns values form 0 to n - 1 , so your loop will run with the values 0 , 1 , 2 , and 3 . range(n)0n - 1返回值,因此您的循环将以值0123运行。

First loop iteration:第一次循环迭代:

  • i is 0 i0
  • lst[i] = lst[i - 1] => lst[0] = lst[0 - 1] => lst[0] = lst[-1] lst[i] = lst[i - 1] => lst[0] = lst[0 - 1] => lst[0] = lst[-1]
  • lst is now [4, 2, 3, 4] lst现在是[4, 2, 3, 4]

Second loop iteration:第二次循环迭代:

  • i is 1 i1
  • lst[i] = lst[i - 1] => lst[1] = lst[1 - 1] => lst[1] = lst[0] lst[i] = lst[i - 1] => lst[1] = lst[1 - 1] => lst[1] = lst[0]
  • lst is now [4, 4, 3, 4] lst现在是[4, 4, 3, 4]

Third loop iteration:第三次循环迭代:

  • i is 2 i2
  • lst[i] = lst[i - 1] => lst[2] = lst[2 - 1] => lst[2] = lst[1] lst[i] = lst[i - 1] => lst[2] = lst[2 - 1] => lst[2] = lst[1]
  • lst is now [4, 4, 4, 4] lst现在是[4, 4, 4, 4]

Fourth loop iteration:第四次循环迭代:

  • i is 3 i3
  • lst[i] = lst[i - 1] => lst[3] = lst[3 - 1] => lst[3] = lst[2] lst[i] = lst[i - 1] => lst[3] = lst[3 - 1] => lst[3] = lst[2]
  • lst is now [4, 4, 4, 4] lst现在是[4, 4, 4, 4]

Swapping has been proposed.已提议交换。 Don't do that:不要这样做:

def func(l):
    for i in range(len(l) // 2):
        l[i], l[-i - 1] = l[-i - 1], l[i]

    return l

# func([1, 2, 3, 4]) -> [4, 3, 2, 1]

To move the last element of a given list/array to the first position, as you've described as your desired output, use blhsing's implementation , if your input is a linked list.要将给定列表/数组的最后一个元素移动到第一个 position,正如您所描述的所需 output,如果您的输入是链表,请使用blhsing 的实现 Python lists are linked lists, and so blhsing's implementation is an efficient one for those. Python 列表是链表,因此 blhsing 的实现对它们来说是一种有效的实现。 If your input is a contiguous array, like a Numpy array, use this:如果您的输入是连续数组,例如 Numpy 数组,请使用以下命令:

def func(l):

    l_last = l[len(l) - 1]

    for i in range(len(l) - 1, 0, -1):
        l[i] = l[i - 1]

    l[0] = l_last

    return l

Both of our implementations mutate the input list/array.我们的两个实现都会改变输入列表/数组。

Why does your function output [4, 4, 4, 4] ?为什么你的 function output [4, 4, 4, 4]
i_max = len(<list>) - 1
<list>[-i] = <list>[len(<list>) - i] . <list>[-i] = <list>[len(<list>) - i]
for i in range(len(<list>)) => i_n in { 0 , 1 , ... , i_max } for i in range(len(<list>)) => i_n in { 0 , 1 , ... , i_max }
i_n = 0 => <list>[0] = <list>[i_max - 1] . i_n = 0 => <list>[0] = <list>[i_max - 1]
If <list> = [1, 2, 3, 4] , then [1, 2, 3, 4][0] = [1, 2, 3, 4][3] = [4, 2, 3, 4] .如果<list> = [1, 2, 3, 4] ,则[1, 2, 3, 4][0] = [1, 2, 3, 4][3] = [4, 2, 3, 4] .
In the next iterations, you will repeatedly replace the i th with the i-1 th element, so that you get:在接下来的迭代中,您将重复地将第i个替换为第i-1个元素,这样您就可以得到:
[4, 2, 3, 4] => [4, 4, 3, 4] => [4, 4, 4, 4] => [4, 4, 4, 4] . [4, 2, 3, 4] => [4, 4, 3, 4] => [4, 4, 4, 4] => [4, 4, 4, 4]

暂无
暂无

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

相关问题 如何将 lst2 中存在的 lst1 中的项目移动到 Python 中 lst1 的末尾? - How do I move items from lst1 that are present in lst2 to the end of lst1 in Python? [浮动(i)为我在lst] - [float(i) for i in lst] 使用for循环迭代并引用lst [i]时发生TypeError / IndexError - TypeError/IndexError when iterating with a for loop, and referencing lst[i] 我想使用 for 循环从列表中删除重复项。我在这里遇到索引超出范围错误:if lst[i]==lst[j]: - I want to remove duplicates from the list using for loop.I am getting index out of bound error here:if lst[i]==lst[j]: 如何让 lst1 按字母顺序排列,同时与 lst2 的顺序相同 - How do I get lst1 to be alphabetical while being in the same order as lst2 如何获取此 Python 代码以将字符串 email_one 中出现的 lst1 中的所有项目替换为 lst2 中的相应索引元素? - How can I get this Python code to replace all the items in lst1 that appear in the string email_one with the corresponding index element in lst2? 在Selenium Python Webdriver中,我无法下载扩展名为.lst的文本文件 - In selenium python webdriver, I'm not able to download a text file with a .lst extension 如何获得 1 到 lst 范围内每个数字的排列? - How can I get the permutations for every number within range 1 to lst? Python,函数,这是怎么回事? 如果 lst1[index] != lst2[len(lst2) - 1 - index] - Python, functions, what is going on here? if lst1[index] != lst2[len(lst2) - 1 - index] 检查列表lst是否是python中的几何序列 - Check list lst if it's a geometric sequence in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM