Python:对象不可订阅

时间:2018-01-16 14:58:36

标签: python

在我的代码中,我生成了数字的组合,之后我将它们混洗并想要一次弹出每个元素并对其进行一些操作,但是当我尝试弹出一个元素时,我得到一个像 “x = lst [0] [0] TypeError:'int'对象不可订阅“。 有什么问题可以帮助我,因为我是python的新手。 谢谢!

temp = []

while i<=value:
    while j<=value:
        lst = [i,j]
        lst=list(itertools.combinations(lst,2))
        temp = temp+lst
        j=j+1
    i=i+1
    j=1

shuffle(temp)


while a<sqrvalue:
    lst = list(temp.pop())

    x = lst[0][0]
    y = lst[0][1]

    w1 = w*(x-1)
    w2 = w*x

    h1 = h*(y-1)
    h2 = h*y

1 个答案:

答案 0 :(得分:0)

正如您在评论中提到的,您希望temp具有以下结构:

[[(4, 2)], [(4, 4)], [(2, 2)], [(1, 4)], [(1, 3)], ... ]

但它有结构:

[(4, 2), (4, 4), (2, 2), (1, 4), (1, 3), ... ]

当你从temp弹出一个项目时,你会尝试

lst = list(temp.pop()) 
x = lst[0][0]
y = lst[0][1]

而你应该做什么

lst = list(temp.pop()) # lst is a two item tuple
x = lst[0]
y = lst[1]

甚至更好

x, y = temp.pop() # this is called tuple unpacking

temp具有结构的原因是用

构建的
temp = temp+lst

由于temp是一个列表而lst是一个包含单个元组[(1, 3)]的列表,因此结果是一个新的列表,其中添加了一个元组。要创建数据结构,您可能想要temp.append(lst),但正如评论中所讨论的那样,您应该这样做:

import random
import product

temp = list(itertools.product(range(1, 5), 2))
random.shuffle(temp)