簡體   English   中英

創建列表時語法無效

[英]Invalid syntax when creating lists

因此,我試圖創建3個不同的列表之一,1k,10k之一,以及100k項目中的一個,長度填充了1到1000萬的隨機數,但我似乎無法弄清楚為什么它一直說它無效的語法。 到目前為止,我有:

編輯:好吧它似乎修復了無效的語法問題與一些調整但仍然給了我:

Traceback (most recent call last):
  File "C:/Python32/funtime.py", line 16, in <module>
    print (list[1])
TypeError: 'type' object is not subscriptable

這正是我輸入的內容:

import random

def createlist(a):

    blist =[]
    count=0
    while count <= a:

        blist.append(random.randint(1,10000000))
        count= count+1
    return blist;


list1= createlist(10000);

print (list[1])
Traceback (most recent call last):
  File "C:/Python32/funtime.py", line 16, in <module>
    print (list[1])
TypeError: 'type' object is not subscriptable

類型type對象確實不是可訂閱的。 list是內置列表類的名稱,它是type的實例。 下標它沒有任何意義,因此顯然不是你打算做的。

你的意思是print (list1[1]) list1是綁定到createlist(10000)創建的列表對象的名稱。

找到這些錯誤的訣竅是查看Python給你的錯誤消息。 它告訴你確切的問題,以及它為什么是一個問題。 所有缺失的是實現list不是您想要下標的對象的名稱。

以下在我的系統上工作正常。

import random

def createlist(a):

    blist =[]
    count= 0
    while count <= a:
        blist.append(random.randint(1,1000000))
        count=count+1
    return blist

list1= createlist(10000)

print list1[1]

http://ideone.com/SL2bL < - 在這里試試吧。

我可能會這樣做

import random

def createlist(a):

    return [random.randint(1,1000000) for i in xrange(a)]


list1= createlist(10000)

print list1[1]

或者可能只是跳過這個功能..

list1 = [random.randint(1,1000000) for i in xrange(a)]
print list1[1]

更短的版本是:

>>> import random
>>> def create_list(length):
...     return [random.randint(1,1000000) for _ in range(length)]

這表明了一些事情:

  1. 循環x次的更緊湊的方法( for _ in range(length) idiom)
  2. 列表推導創建列表,而不是重復調用append
  3. 當您需要變量時,使用_作為變量名,而不是其中的實際數據。 這是一種常見的慣例,在列表推導中最常出現。 不使用它不是一個問題,但它經常出現足以讓人意識到它。

給@mgilson提示他對另一個答案的評論,這個答案讓我想起了_慣例。

使用列表理解(它的方式betta,讓你看起來親,哈哈)

[random.randint(1, 1000000) for i in range(10000)]

正如其他一些答案所述,你可以輕松地將列表理解用於這樣的事情(所謂的Pythonic方式):

somelist = [random.randint(1, 1000000) for i in xrange(10000)]

列表理解在Python中很快,因為它由底層C代碼執行。 而且,使用xrange可以提高內存效率。

注意:按照慣例,當Python中沒有使用循環控制變量時,它被命名為_

somelist = [random.randint(1, 1000000) for _ in xrange(10000)]

首先,除非您正在評估復雜的表達式while否則您不會使用paren。

接下來,您使用分號返回blist 不必要。

最后......為什么不使用for循環?

import random

def createlist(a): 
    blist =[]

    for x in xrange(a):
        blist.append(random.randint(1,1000000))

    return blist

list1= createlist(10000)

print list1[0]

暫無
暫無

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

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