有没有一种方法可以在每次迭代时将新列表附加到现有列表中?

Is there a way through which I can append the new list into the existing list on each while iteration?

**有人可以帮助我更好的方法吗?

This is my output.The user has to input whether he has a new process to enter if yes then enter new process and it must get appended to a new list.But in my case after every new iteration of while it gets appended to the first list instead.


Enter process name: 1
Enter process Arrival Time: 3
Enter Execution Time: 2

[['1', 3, 2]]
Enter process name: 2
Enter process Arrival Time: 4
Enter Execution Time: 3

[['1', 3, 2], ['2', 4, 3]]
enter new processy
ENTER TOTAL NUMBER OF PROCESSES: 1
Enter process name: 3
Enter process Arrival Time: 2
Enter Execution Time: 3

[['1', 3, 2, '3', 2, 3], ['2', 4, 3], []]
enter new process

----------------------------------------------
>This is my code 

a = 0
#p = [['p1', 0, 2], ['p2', 1, 2], ['p3', 5, 3], ['p4', 6, 4]]
a2 = [0]
completion_time=[]
pp = []
tat=[]
waiting_time=[]
p = []
total_wtime = 0
n=0

def addnew():
    n = int(input('ENTER TOTAL NUMBER OF PROCESSES: '))
    for i in range(n):
        p.append([])
        p[i].append(input('Enter process name: '))
        p[i].append(int(input('Enter process Arrival Time: ')))

        p[i].append(int(input('Enter Execution Time: ')))
        print('')
        print(p)

ans="y"
while(ans=="y"):
    addnew()
    ans = input("enter new process")

这是因为,在每次调用 addnew 时,您都会附加一个新的空列表,然后您 return 到第一个列表以附加新数据。无需从 0 到 n 访问 p[i],您只需处理新列表。获得所有新数据后,然后 将生成的新列表附加到 p 的末尾。

def addnew():
    n = int(input('ENTER TOTAL NUMBER OF PROCESSES: '))
    for i in range(n):
        newlist = []
        newlist.append(input('Enter process name: '))
        newlist.append(int(input('Enter process Arrival Time: ')))

        newlist.append(int(input('Enter Execution Time: ')))
        print('')
        print(newlist)
    p.append(newlist)

您的索引变量 i 每次都从 0 循环到 n-1,即使您在现有列表中添加元素也是如此。

最好的方法可能只是将新元素添加到新列表,然后按照 Prune 的建议追加它。但是,如果您正在寻找对现有代码的最小更改,请更改行:

    for i in range(n):

    for i in range(len(p), len(p) + n):

这将确保当您再次调用 addnew 时,索引会继续从您停止的地方开始,而不是再次从 0 开始。


如果您 决定采用附加到新列表的方法(请参阅 Prune 的回答),那么您可以考虑进行额外的更改,前提是您的变量 i 将不再在循环内使用,将调用它 _ 而不是 i,因为这是虚拟变量的常规命名。这不适用于您现有的代码,因为您正在使用它来索引 p.


这里还有另一种选择...

您可以将 p[i] 更改为 p[-1](即 last 元素)。然后你的循环变量只是一个虚拟变量,它也可能像现在一样从 0 循环到 n-1,因为我们不关心提供的值是 n 次迭代。

    for _ in range(n):
        p.append([])
        p[-1].append(input('Enter process name: '))
        p[-1].append(int(input('Enter process Arrival Time: ')))
        # ... etc ...

同样,这只是对现有代码进行最小更改的建议。最干净的方法仍然是 newlist 方法。