简体   繁体   中英

Calculating sum of a certain group of integers in a list

So im very new to python and am trying to make a text based rpg-like thing that involves a first room with 2 exits (left or right) and each row of rooms afterwards has the amount of integers of the sum of the last one and each variable is a random integer from 0 to 3(amount of exits), like so:

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)

This works fine however navigation has proven hard.

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)])

What i am attempting to do here is finding the sum of every integer in the list that comes before the current 'room'. But i have no idea how to do this! Any help would be appreciated, many thanks!

It seems as if you are looking for something like:

import random

big_list = [[2]]

for _ in range(1,5):  # increase to create more "rooms"
    big_list.append( [random.randint(0,3) for _ in range(sum(big_list[-1]))])

total = 0
for inner in big_list:
    print(inner, "before:", total)
    total += sum(inner) 

To produce lists like:

[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

Due to randomness you also might get:

[2] before: 0
[0, 1] before: 2
[0] before: 3
[] before: 3
[] before: 3

A partial sum inside a list can be got by a generator expression inside sum or list slicing and sum:

lol = [[1,2,3], [4,5,6,7,8,9,10,11,12], [13,14,15,16,17]]

idx_in_lol   = 1      # [4,5,6,7,8,9,10,11,12]

idx_in_inner = 5      # [4,5,6,7,8,***9***,10,11,12]

# generator expression and enumerate     
s1 = sum( i if idx < idx_in_inner else 0 for idx,i in enumerate(lol[idx_in_lol]))

# or by slicing
s2 = sum( lol[idx_in_lol][:idx_in_inner] )

print(s1, s2) 

Output:

30 30 #  4+5+6+7+8 = 30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM