2

您能否建议一种将变量的值应用于从元素 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
4

2 回答 2

5

您可以像这样创建一个列表pts_alloc并将其分配给切片

num_weighted[6:] = [pts_alloc for i in range(len(num_weighted) - 6)]
于 2013-11-09T15:20:22.527 回答
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

于 2013-11-09T15:18:46.823 回答