[英]How do I iterate over a list of strings and identify ints and floats and then add them to a list?
[英]How can I iterate over a list of strings with ints in python?
我是使用python進行編程和一般編程的新手,並且遇到以下問題:
b=["hi","hello","howdy"]
for i in b:
print i
#This code outputs:
hi
hello
howdy
我怎樣才能使迭代變量是一個整數,所以它可以按以下方式工作?
b=["hi","hello","howdy"]
for i in b:
print i
#I want it to output:
0
1
2
Python的方式是enumerate()
:
for index, item in enumerate(b):
print index, item
還有range(len(b))
,但是您幾乎總是會在循環主體中檢索item
,因此enumerate()
在大多數情況下是更好的選擇:
for index in range(len(b)):
print index, b[index]
b=["hi","hello","howdy"]
for count,i in enumerate(b):
print count
您可以始終這樣做:
b=["hi","hello","howdy"]
for i in range(len(b)):
print i
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.