簡體   English   中英

用浮點值迭代列表,然后打印相同的列表

[英]Iterate the list with float value and then print the same list

我有一個帶有float值的列表float_list = [0.2, 1.2, 1.5, 0.7, 0.9]

首先我要迭代float_list的值,然后這些值乘以 2 ,最后我要將結果打印到列表中,期望結果必須是[0.4, 2.4, 3.0, 1.4, 1.8] 0.4,2.4,3.0,1.4,1.8 [0.4, 2.4, 3.0, 1.4, 1.8]

但是我收到一個TypeError: 'float' object is not iterable這是我的代碼

我的密碼

float_list = [0.2, 1.2, 1.5, 0.7, 0.9]
for i in float_list:
    print([list_num*2 for list_num in i])

所需結果

[0.4, 2.4, 3.0, 1.4, 1.8]

錯誤

Traceback (most recent call last):
  File "F:/python-practise/for.py", line 3, in <module>
    print([list_num*2 for list_num in i])
TypeError: 'float' object is not iterable

注意:我也嘗試將i作為字符串str(i) print([list_num*2 for list_num in str(i)]) str(i)中 print([list_num*2 for list_num in str(i)])但是這樣做是在控制台中得到的

['00', '..', '22']
['11', '..', '22']
['11', '..', '55']
['00', '..', '77']
['00', '..', '99']

現在我只是被卡住了,請幫助我獲得期望的結果。

您正在混合循環和列表推導。 在您的循環中, i已經是列表的單個元素,即一個數字。 應該只使用一個循環?

float_list = [0.2, 1.2, 1.5, 0.7, 0.9]
for i in float_list:
    print(i * 2)

... 列表理解:

print([i * 2 for i in float_list])
for i in float_list:
    print([list_num*2 for list_num in i])

我將是一個浮動對象,因為浮動對象在列表中。 因此,您無法遍歷浮點數,因為它不是列表。 因此,“對於我中的list_num將失敗。

只是這樣做:

float_list = [0.2, 1.2, 1.5, 0.7, 0.9]

print([list_num*2 for list_num in float_list])

如果您有一個簡單列表(不是列表列表),則可以使用循環或列表理解,但不能同時使用兩者。

只需刪除

for i in float_list:

而且你很好。

請注意,您有兩個for循環。 您只需要一個。

>>> float_list = [0.2, 1.2, 1.5, 0.7, 0.9]
>>> new_list = [list_num*2 for list_num in float_list]
>>> print(new_list)
[0.4, 2.4, 3.0, 1.4, 1.8]

我建議您在打印時打開包裝:

>>> print(*new_list)
0.4 2.4 3.0 1.4 1.8

內部列表理解會導致錯誤,因為您在單個float項上應用了for循環,即您無法在float對象上進行迭代=>這就是錯誤所指示的內容。

解:

使用列表理解:

>>> float_list
[0.2, 1.2, 1.5, 0.7, 0.9]
>>> print([list_num*2 for list_num in float_list])
[0.4, 2.4, 3.0, 1.4, 1.8]

或像這樣的循環

>>> new_list=[]
>>> for i in float_list:
...     new_list+=[i*2]
... 
>>> new_list
[0.4, 2.4, 3.0, 1.4, 1.8]
>>> 

我建議使用map()將函數映射到列表的每個元素:

>>> float_list
[0.2, 1.2, 1.5, 0.7, 0.9]
>>> list(map(lambda x:x*2, float_list))
[0.4, 2.4, 3.0, 1.4, 1.8]
>>> 

我認為這會解決

result = [2*i for i in float_list]
print(result)

要么

print([i*2 for i in float_list])    

希望能幫助到你。 快樂編碼:)

我將分兩個步驟處理任務:

# Declare the variables
float_list = [ ] # your present array
float_double_array = [ ] # your to be new array
  1. 迭代當前列表-如下所示的float_list,然后乘以2,然后將結果附加到float_double_array

     for index_item in float_list: double_item=index_item * 2 float_double_array.append(double_item) 
  2. 現在,您可以使用新的float_double_array及其索引值,如下所示。

     for double_floats in float_double_array: try: print " ".join(double_floats) #handles python 2 except: print (" ".join(double_floats)) #handles python 3 

最后,如有任何疑問,請詢問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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