gpt4 book ai didi

python - 在python中循环包含数组的链表

转载 作者:太空宇宙 更新时间:2023-11-03 21:34:47 25 4
gpt4 key购买 nike

我正在努力弄清楚如何使用循环来运行一个列表,该列表包含 4 个数组值,即“a_value”、“b_value”、“c_value”、“d_value”。此列表中的每个数组都有 23 个元素。我正在寻找的结果是循环运行列表,添加每个数组的所有 23 个元素。例如。 “a_value”总计,然后“b_value”总计,依此类推。这就是我到目前为止所拥有的。谢谢你们。

class node():
def __init__(self, dataval = None):
self.dataval = dataval
self.nextval = None

class linked_list():
def __init__(self):
self.headval = None

def listprint(self):
printval = self.headval
while printval != None:
print (printval.dataval)
printval = printval.nextval


arraylist = linked_list()
arraylist.headval = node(a_value) # each '""_value' has 23 integer values
in them
e2 = node(b_value)
e3 = node(c_value)
e4 = node(d_value)

arraylist.headval.nextval = e2
e2.nextval = e3
e3.nextval = e4

arraylist.listprint()

i = 1
x = 1
total_a = 0
total_b = 0
total_c = 0
total_d = 0

for n in arraylist:
for z in range(len(n)-1)
value_a = int(a_value[i])
total_a+=value_a
i+= 1
x+=1

最佳答案

你可以尝试这样的事情:

    a_value = [1,2,3]
b_value = [4,5,6]
c_value = [7,8,9]
d_value = [10,11,12]

class node():
def __init__(self, dataval = None):
self.dataval = dataval
self.nextval = None


class linked_list():
def __init__(self):
self.headval = None

def listprint(self):
printval = self.headval
while printval != None:
print (printval.dataval)
printval = printval.nextval


arraylist = linked_list()
arraylist.headval = node(a_value)
e2 = node(b_value)
e3 = node(c_value)
e4 = node(d_value)

arraylist.headval.nextval = e2
e2.nextval = e3
e3.nextval = e4

node = arraylist.headval # fetch head node
nextval = node.nextval # fetch next to node
list = []
list.append(node.dataval) # enter all head list

while nextval: # this loop will break as nextval is none
node = node.nextval # node now becomes next and repeat
if hasattr(node, 'nextval'):
nextval = node.nextval
else:
nextval = None
list.append(node.dataval)

sum = 0

for x in list: # sum in the end or break into 23 for all separate
for y in x:
sum+=y

print(list, sum)

#OUTPUT [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] 78

工作正常:)

关于python - 在python中循环包含数组的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53302144/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com