我是新來的Python基本蟒蛇可能有人告訴我什麼是這個代碼的問題:您定義n
是一個零長度list
for循環
#!/usr/bin/python
nl=[]
for x in range(1500, 2700):
i=0
if (x%7==0) and (x%5==0):
nl[i]=x
i=i+1
print (','.join(nl))
我是新來的Python基本蟒蛇可能有人告訴我什麼是這個代碼的問題:您定義n
是一個零長度list
for循環
#!/usr/bin/python
nl=[]
for x in range(1500, 2700):
i=0
if (x%7==0) and (x%5==0):
nl[i]=x
i=i+1
print (','.join(nl))
,但你寫(假定)元素超出列表的末尾。解決這個問題
一種方法是改變n
來分配:
n = [None]*1200
不能任意設定指標爲0長度列表。
使用列表,並追加:
# nl[i]=x <- this won't work
nl.append(x)
因爲你似乎不打印時使用實際的指標,這應該工作。請注意,您將需要使用
print(",".join(map(str, nl)))
作爲連接將無法在整數。
如果你確實需要索引,我會建議使用字典。
nl = {}
low = 1500
high = 2700
for x in range(low, high):
if (x % 7 == 0) and (x % 5 ==0):
nl[x-low] = x
print(','.join(map(str, nl.values())))
注意在這種情況下,值將不能進行排序。如果你想他們是那麼你可以
print(','.join(map(str, sorted(nl.values()))))
而且對它們進行排序,你現在可以
for index, value in sorted(nl.items()):
nl=[]
for x in range(1500, 2700):
if (x%7==0) and (x%5==0):
nl.append(str(x))
print (','.join(nl))
而不是使用索引迭代索引和值(即使按排序順序)你可以嘗試在列表中使用附加方法,這在這種情況下非常有用。請嘗試以下方法
nl=[]
for x in range(1500,2700):
if x%7==0 and x%5==0 :
m.append(x)
print(nl)
希望它有所幫助。
除了其他答案中提到的零長度列表問題。在循環的每次迭代中,您都設置了i = 0
。所以你總是改變列表中的相同元素(第一個)。
使用此程序來代替:
nl=[]
for x in range(1500, 2700):
if (x%7==0) and (x%5==0):
nl.append(x)
print nl
它的工作原理如下:
>>> ================================ RESTART ================================
>>>
[1505, 1540, 1575, 1610, 1645, 1680, 1715, 1750, 1785, 1820, 1855, 1890, 1925, 1960, 1995, 2030, 2065, 2100, 2135, 2170, 2205, 2240, 2275, 2310, 2345, 2380, 2415, 2450, 2485, 2520, 2555, 2590, 2625, 2660, 2695]
>>>
代碼的問題:
nl
)。您必須使用append()
方法來追加其長度。,
字符的列表中的整數。你根本不需要它。打印列表本身。:)您在for循環中設置了i = 0
。相反,將它設置在外部並增加。
此外,在Python中,你可以使用一個所謂list comprehension得到同樣的結果在一條線:
nl = [x for x in range(1500, 2700) if (x%7==0) and (x%5==0)]
這提供了int
列表。要打印它,你需要轉換的int
到string
:
print(','.join(map(str, nl)))
或者你也可以直接創建一個字符串列表:
nl = [str(x) for x in range(1500, 2700) if (x%7==0) and (x%5==0)]
print(','.join(nl))
如果你想要的是打印出來,一切都可以在完成一條線:
print(','.join(str(x) for x in range(1500, 2700) if (x%7==0) and (x%5==0)))