2017-10-28 54 views
-2

我是python中的新成員。我有一個for loop其中我有if ...:條件。列印經過For循環的項目? python 2.7

我想打印經過for循環的項目(列表)。

理想情況下,項目應該用空格或逗號分隔。這是一個簡單的例子,打算用arcpy打印出加工後的shapefile文件。

假例如:

for x in range(0,5): 
    if x < 3: 
     print "We're on time " + str(x) 

我試了一下沒有內部和iffor環成功:

print "Executed " + str(x) 

預計回去(而不是在list格式),也許是通過什麼像arcpy.GetMessages()

Executed 0 1 2 
+0

您使用的是什麼版本的Python? –

+0

2.7,我更新了我的問題 – maycca

+0

ArcPy似乎與您的問題無關,因爲沒有答案包含它。 – PolyGeo

回答

1
phrase = "We're on time " 

# create a list of character digits (look into list comprehensions and generators) 
nums = [str(x) for x in range(0, 5) if x < 3] 

# " ".join() creates a string with the elements of a given list of strings with space in between 
# the + concatenates the two strings 
print(phrase + " ".join(nums)) 

注意。 downvotes的原因可以幫助我們的新用戶瞭解應該如何。

+0

感謝您的支持,解釋downvotes的原因 – maycca

1

記錄你x的列表中,並打印出此列表中底:

x_list = [] 
for x in range(0,5): 
    if x < 3: 
     x_list.append(x) 
     print "We're on time " + str(x) 
print "Executed " + str(x_list) 
+0

我有一個錯誤返回:AttributeError:'int'object has no attribute'append' – maycca

+0

對不起,請嘗試更新後的代碼。 –

+0

謝謝!現在它工作。是否有可能無法獲得物品清單,但只有0 1 2? – maycca

0

如果使用Python3你可能只是做這樣的事情..

print("Executed ", end='') 
for x in range(0,5): 
    if x < 3: 
     print(str(x), end=' ') 
print()