TypeError:只能分配一个iterable - 要列出的值

时间:2013-11-09 15:16:45

标签: python python-3.x

您能否建议一种方法将变量的值应用于从变量定义的元素6到结尾的列表中?

也许我的代码会更好地解释它(Python 3)

#get user input as to size of range
range_size = 0
if range_size == 0:
    try:
        range_size = int(input('Size of Range?: '))
    except ValueError:
        print('That was not an integer!')
        range_size = 0

#set base value for each number in range_size
base_value = int(100 / range_size)

print(base_value)

#create list of base values
num_weighted = [base_value] * range_size
num_weighted[0] = round(base_value * 1.8, 1)
num_weighted[1] = round(base_value * 1.6, 1)
num_weighted[2] = round(base_value * 1.5, 1)
num_weighted[3] = round(base_value * 1.3, 1)
num_weighted[4] = round(base_value * 1.15, 1)
num_weighted[5] = round(base_value * 1.1, 1)

print(num_weighted)
# redistribute the difference of the sum top 6 and 100, apply to rest of range
top6 = (sum(num_weighted[0:6]))
not_top6 = range_size - 6
pts_alloc = round((100 - top6) / not_top6, 1)
print(pts_alloc)

#attempt 1
num_weighted[6:] = pts_alloc

#attempt 2
#num_weighted[6:(range_size + 1)] = pts_alloc

#attempt 3
#s = slice(6, not_top6)
#num_weighted[s] = pts_alloc

2 个答案:

答案 0 :(得分:4)

您可以创建pts_alloc的列表,并将其分配给此片段

num_weighted[6:] = [pts_alloc for i in range(len(num_weighted) - 6)]

答案 1 :(得分:2)

使用list.append()

num_weighted.append(pts_alloc)

您只能将一个可迭代分配给切片;具有0或更多值的东西,而不是一个特定值。

我不预先建立列表然后替换所有内容;只是做:

num_weighted = [
    round(base_value * 1.8, 1)
    round(base_value * 1.6, 1)
    round(base_value * 1.5, 1)
    round(base_value * 1.3, 1)
    round(base_value * 1.15, 1)
    round(base_value * 1.1, 1)
]

并使用带有生成器的pts_alloc list.extend()扩展列表:

num_weighted.extend(pts_alloc for _ in range(range_size - 6)) 

现在您有一个长度为range_size的列表。