0
list1 = [1,2,3,4,5,6,7,8,9]
def replace():

    input_list = input("Enter three numbers separated by commas: ")
    list2 = input_list.split(',')
    list2 = [int(x.strip())for x in list2]

    del list1[-3:]
    list1.insert(0,list2)

    print(list1)

for input 12,13,14 this gives as a result [[12,13,14],1,2,3,4,5,6] Firstly I would like to have a 'flat' list as the result and can't seem to get this right [12,13,14,1,2,3,4,5,6]. I can get the last value entered as part of the list by removing the square brackets from the list2=[int(x.strip()) for...] statement, gives [14,1,2,3,4,5,6]. My second wish is that I can change the initial list permanently ie [12,13,14,1,2,3,5,6] becomes list1 that is called in the first place. Do I need to save this as a csv file and write to it? I am very new to this, so please forgive me if this is a very simple or stupid batch of questions.

4

1 回答 1

1

I believe this is what you want:

In [11]: list1 = [1, 2, 3, 4, 5, 6]

In [12]: list2 = [12, 13, 14]

In [13]: list1[0:0] = list2

In [14]: list1
Out[14]: [12, 13, 14, 1, 2, 3, 4, 5, 6]

The slice operation changes list1 in-place, so the variable isn't simply pointing at a new list. I think that's what you meant by "permanently"?

于 2012-11-14T15:46:38.337 回答