2017-10-28 88 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()