[英]Why doesn't python print everything I wrote into it?
I was doing some exercises in python python and I bumped into a problem.我在 python python 做一些练习,我遇到了一个问题。 I already printed a list reversed and I wanted to print the reversed elements in separate lines too but for some reason it only prints the first one and if I put the first print into comment it prints out the loop just fine.
我已经打印了一个反转的列表,我也想在不同的行中打印反转的元素,但由于某种原因它只打印第一个,如果我把第一个打印到评论中,它打印出循环就好了。 Why?
为什么?
def main():
pass
if __name__ == '__main__':
main()
list1 = [10, 20, 30, 40, 50]
def reverse_list(l1):
l2 = []
for i in range(len(l1)):
l2.append(l1.pop())
return l2
print(reverse_list(list1))
pass
def reverse_print(l):
listr = reversed(l)
for j in listr:
print(j)
reverse_print(list1)
print("Complete...")
In python, data types are divided into mutable and immutable types: python中,数据类型分为可变和不可变类型:
a = [1,2,3,4]
a_ref = a
print(a) # [1,2,3,4]
a_ref[0] = 5
print(a) # [5,2,3,4]
It can be seen from the above code从上面的代码可以看出
for example:例如:
a = [1,2,3,4]
def somefunc(a2):
a2.append(5)
print(a) # [1,2,3,4]
somefunc(a)
print(a) # [1,2,3,4,5]
Normally, it won't change a by calling somefunc(a)
通常,它不会通过调用
somefunc(a)
来改变 a
BUT但
Since a2 is a reference to a and points to the same memory location, when a2 is modified, it will also be modified to a由于a2是对a的引用,指向同一个memory位置,所以修改a2时,也会修改为a
in your code:在你的代码中:
when you calling reverse_list(list1)
, l1 is a reference to list1, when you pop the element from l1, it will also pop the element in list1当你调用
reverse_list(list1)
时,l1 是对 list1 的引用,当你从 l1 中弹出元素时,它也会弹出 list1 中的元素
so after called reverse_list(list1)
, list1 is empty, that why reverse_print(list1)
do not print anything所以在调用
reverse_list(list1)
之后,list1 是空的,这就是为什么reverse_print(list1)
不打印任何东西
Sollution解决方案
def reverse_list(l1):
l1_copy = l1[:] # copy the whole list
l2 = []
for i in range(len(l1_copy)):
l2.append(l1_copy.pop())
return l2
when you call l1_copy = l1[:]
than l1_copy won't point to same memory location so l1 and list1 won't modified when modifica l1_copy当您调用
l1_copy = l1[:]
时,l1_copy 不会指向相同的 memory 位置,因此在修改 l1_copy 时 l1 和 list1 不会被修改
PS: english is my second langage, so there maybe have some gramma mistake, please excuse me PS:英语是我的第二语言,所以可能有一些语法错误,请原谅
at the second print list1
has been emptied out from using the pop()
method in reverse_list
.在第二次打印时,
list1
已通过使用reverse_list
中的pop()
方法清空。
to reverse a list perhaps you should use the reverse()
method like the following example:要反转列表,也许您应该使用
reverse()
方法,如下例所示:
List1 = [1,2,3]
List1.reverse()
print(List1) # [3,2,1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.