[英]While loop, double numbers in list
How would I produce a while loop, to double and therefore change the numbers in the following list? 我将如何产生while循环,以加倍并因此更改以下列表中的数字?
Thank you. 谢谢。
numberList = [3, 5, 6, 2, 1, 5, 7, 4]
This was my attempt 这是我的尝试
numberList = [3, 5, 6, 2, 1, 5, 7, 4]
while numberList == numberList:
numberList == numberList * 2
print (numberList)
break
Although not the best way to solve the problem, this is a way of doing it using a while loop: 尽管这不是解决问题的最佳方法,但这是一种使用while循环的方法:
numberList = [3, 5, 6, 2, 1, 5, 7, 4]
i=0
while i < len(numberList):
numberList[i] *= 2
i += 1
>>> numberList
[6, 10, 12, 4, 2, 10, 14, 8]
Notice that multiplying a list by an integer will output a list repeating the elements, so your attempt actually does something like this: 请注意,将列表乘以整数将输出一个重复元素的列表,因此您的尝试实际上是这样的:
>>> [1,2,3]*2
[1, 2, 3, 1, 2, 3]
You can map list with a lambda function to perform the desired function! 您可以使用lambda函数映射列表以执行所需的功能!
numberList= [3, 5, 6, 2, 1, 5, 7, 4]
print map(lambda x:x*2,numberList)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.