计算列表中特定整数组的总和

因此,我对python非常陌生,并且我正在尝试制作一个基于文本的类似rpg的东西,该事物涉及具有2个出口(左侧或右侧)的第一个房间,之后的每行房间都有最后一个房间之和的整数量,每个变量都是从0到3(退出量)的随机整数, 这样:


a = [2]

print(a)

import random

b = []

for i in range(0,2):

    x = random.randint(0,3)

    b.append(x)

print(b)

b_sum = sum(b)

import random

c = []

for i in range(0,b_sum):

    x = random.randint(0,3)

    c.append(x)

print(c)

c_sum = sum(c)

import random

d = []

for i in range(0,c_sum):

    x = random.randint(0,3)

    d.append(x)

print(d)

d_sum = sum(d)

import random

e = []

for i in range(0,d_sum):

    x = random.randint(0,3)

    e.append(x)

print(e)

e_sum = sum(e)

import random

f = []

for i in range(0,e_sum):

    x = random.randint(0,3)

    f.append(x)

print(f)

f_sum = sum(f)

import random

g = []

for i in range(0,f_sum):

    x = random.randint(0,3)

    g.append(x)

print(g)

这工作正常,但导航已被证明很难。


rowlist = [a,b,c,d,e,f,g,h,ii]

row = (rowlist[0])


room = (a[0])

print(room)

if room == 2:

    door=str(input("left or right"))

    if door == "left":

        roomsum = sum(row[row < room (+1)])

我在这里试图做的是找到当前“房间”之前的列表中的每个整数的总和。但我不知道如何做到这一点!任何帮助将不胜感激,非常感谢!


慕姐8265434
浏览 76回答 1
1回答

慕的地10843

看起来你正在寻找这样的东西:import randombig_list = [[2]]for _ in range(1,5):&nbsp; # increase to create more "rooms"&nbsp; &nbsp; big_list.append( [random.randint(0,3) for _ in range(sum(big_list[-1]))])total = 0for inner in big_list:&nbsp; &nbsp; print(inner, "before:", total)&nbsp; &nbsp; total += sum(inner)&nbsp;生成如下列表:[2] before: 0[3, 1] before: 2[2, 3, 1, 1] before: 6[1, 1, 2, 0, 2, 2, 2] before: 13[2, 3, 0, 2, 3, 2, 2, 1, 0, 2] before: 23由于随机性,您还可能得到:[2] before: 0[0, 1] before: 2[0] before: 3[] before: 3[] before: 3列表中的部分和可以通过 sum 或列表切片和 sum 中的生成器表达式获得:lol = [[1,2,3], [4,5,6,7,8,9,10,11,12], [13,14,15,16,17]]idx_in_lol&nbsp; &nbsp;= 1&nbsp; &nbsp; &nbsp; # [4,5,6,7,8,9,10,11,12]idx_in_inner = 5&nbsp; &nbsp; &nbsp; # [4,5,6,7,8,***9***,10,11,12]# generator expression and enumerate&nbsp; &nbsp; &nbsp;s1 = sum( i if idx < idx_in_inner else 0 for idx,i in enumerate(lol[idx_in_lol]))# or by slicings2 = sum( lol[idx_in_lol][:idx_in_inner] )print(s1, s2)&nbsp;输出:30 30 #&nbsp; 4+5+6+7+8 = 30
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python