制作列表的本地副本并对其进行修改

2024-09-30 01:27:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一段代码,它接受用户整数输入,并且只在列表中包含数字的一个副本。e、 g

在我的代码中,我不需要在第二个函数中创建一个新列表并返回它,而是需要创建初始列表的本地副本,并对其进行修改,使其只包含一个整数。我不知道该怎么做

def listOfIntegerInput ():
    inputSeq = input("Please enter a space-separated sequence of integers: ")
    integerList= []
    inputSeq = inputSeq.split()
    for entry in inputSeq:
        try:
            integerList.append(int(entry))
        except ValueError:
            continue
    return integerList

def uniqueInts (ListOfValues):
    uniqueInts = []
    for entry in ListOfValues:
        if entry not in uniqueInts:
            uniqueInts.append(entry)
    return uniqueInts



print("This program removes duplicates from a given sequence of integers")
inputSequence = listOfIntegerInput()
finalListOfUniqueInts = uniqueInts(inputSequence)
print(finalListOfUniqueInts)

输出:

This program removes duplicates from a given sequence of integers
Please enter a space-separated sequence of integers: 1 1 2 3 4 5 5
[1, 2, 3, 4, 5]

因此,我只需要修改第二个函数unqiueInts (listOfValues)来修改列表,而不返回列表。我不知道如何制作本地副本并对其进行修改

因此,本质上,最终列表应该是第一个函数生成的同一个对象,只是第二个函数会对其进行变异/修改。然后主程序打印最终列表


@JonClements

这是我通过使用copy函数实现的。这是正确的,还是存在冗余代码或更好的方法(假设代码必须遵循if not in…的算法)

在赋值规则中,它说我需要在第二个函数中从头开始重建初始参数(“为了实现相同的算法,参数列表应该从头开始重建,即必须清空,并逐个添加其(唯一)元素,因此,必须事先制作初始列表的本地副本。”)

def listOfIntegerInput():
    inputSeq = input("Please enter a space-separated sequence of integers: ")
    integerList = []
    inputSeq = inputSeq.split()
    for entry in inputSeq:
        try:
            integerList.append(int(entry))
        except ValueError:
            continue
    return integerList


def uniqueInts(ListOfValues):
    CopyOfListOfValues = ListOfValues[:]
    ListOfValues.clear()
    for entry in CopyOfListOfValues:
        if entry not in ListOfValues:
            ListOfValues.append(entry)


print("This program removes duplicates from a given sequence of integers")
inputSequence = listOfIntegerInput()
uniqueInts(inputSequence)
print(inputSequence)

Tags: ofintegers函数代码in列表def副本

热门问题