Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从列表中删除最后n个元素。我得到一个错误:“quot;ValueError:list。删除(x):x不在列表中;_Python_List - Fatal编程技术网

Python 从列表中删除最后n个元素。我得到一个错误:“quot;ValueError:list。删除(x):x不在列表中;

Python 从列表中删除最后n个元素。我得到一个错误:“quot;ValueError:list。删除(x):x不在列表中;,python,list,Python,List,我在这个代码中有一个错误,我不明白为什么它是错误的 LL = [2,3,4,5,6,2,5,4] print(x[-4:]) def remove_last_elements(the_list): while len(the_list) > 5 in the_list: the_list.remove(the_list[-4:]) print(the_list) remove_last_elements(LL) 输出应为LL=[2,3,4,5]。我需要len

我在这个代码中有一个错误,我不明白为什么它是错误的

LL = [2,3,4,5,6,2,5,4]
print(x[-4:])
def remove_last_elements(the_list):
    while len(the_list) > 5 in the_list:
       the_list.remove(the_list[-4:])
    print(the_list)
remove_last_elements(LL)
输出应为LL=[2,3,4,5]。我需要len()>5,因为我有几个包含不同数量元素的列表(嵌套)

下面是我收到的错误消息:

Traceback (most recent call last):
  File "C:/APPL/DPI/PDF_reader/test_general.py", line 68, in <module>
    remove_last_elements(LL)
  File "C:/APPL/DPI/PDF_reader/test_general.py", line 66, in remove_last_elements
    the_list.remove(the_list[-4:])
ValueError: list.remove(x): x not in list
回溯(最近一次呼叫最后一次):
文件“C:/APPL/DPI/PDF_reader/test_general.py”,第68行,在
删除最后一个元素(LL)
文件“C:/APPL/DPI/PDF_reader/test_general.py”,第66行,在remove_last_元素中
_列表。删除(_列表[-4:])
ValueError:list。删除(x):x不在列表中

是的,您应该对此进行简单的比较。如果列表中有5个以上的元素,请删除最后5个。把它想象成除了最后5个以外的所有东西

if len(the_list) > 5:
    the_list = the_list[:-4]
如果要将列表缩小到不超过5个元素,请将
If
替换为
while


按操作更新澄清

您的任务是删除由5个元素组成的组,直到不超过5个。使用模运算符,这非常简单

final_size = len(the_list) % 5
if final_size = 0:
    final_size = 5

the_list = the_list[:final_size]

您的原始代码有几个结构问题。如果您担心列表中有多少元素,为什么要检查特定元素<_列表中的代码>5正在查找值5,而不是5个元素

其次,您的列表由整数组成,但您正试图删除一个自引用子列表:

the_list.remove(the_list[-4:])

正如您已经知道的,该片段是由五个元素组成的特定列表。您在\u列表中没有子列表,因此无法将其作为元素。如果您想从原始列表中删除每个元素,那么必须依次遍历它们。只需抓取想要保留的列表片段就可以轻松得多。

您不必检查任何条件。只需尝试一下前五个要素:

the_list = the_list[:5]

如果列表中的元素少于五个,则切片运算符将被忽略。

len(列表)>5(列表)
检查列表中是否存在布尔值
len(列表)>5
。这就是你想写的吗?@ForceBru:实际上是比较链接,不检查列表中是否有布尔值,但无论哪种方式都是错误的(下一行也是如此)。如果列表长度大于5,我想删除最后n项。我应该使用if结构吗?@ForceBru它正在检查
(len(列表)>5)和(列表中的5)
@DYZ,这很奇怪。显然,我真的没料到