簡體   English   中英

While循環,列表中的雙精度數字

[英]While loop, double numbers in list

我將如何產生while循環,以加倍並因此更改以下列表中的數字?

謝謝。

numberList = [3, 5, 6, 2, 1, 5, 7, 4]

這是我的嘗試

numberList = [3, 5, 6, 2, 1, 5, 7, 4]

while numberList == numberList:
    numberList == numberList * 2
    print (numberList)
    break

盡管這不是解決問題的最佳方法,但這是一種使用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]

請注意,將列表乘以整數將輸出一個重復元素的列表,因此您的嘗試實際上是這樣的:

>>> [1,2,3]*2
[1, 2, 3, 1, 2, 3] 

您可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM