我有一些用于练习的代码,我需要使用删除命令(我不知道那东西是不是命令,但我不知道它是什么。)我正在使用的服务希望我使用删除命令删除我拥有的二维列表中的一段数据。但我收到此错误:
Traceback (most recent call last):\
File "script.py", line 13, in ‹module\
customer_data. remove (False)\
ValueError: list.remove(x): x not in list
我没有尝试太多,因为该服务只希望我使用删除而不是循环来从列表中删除数据。
first_names = ['Ainsley', 'Ben', 'Chani', 'Depak']
preferred_size = ['Small', 'Large', 'Medium']
preferred_size.append('Medium')
print(first_names)
print('')
print(preferred_size)
print('')
customer_data = [['Ainsley', 'Small', True],['Ben', 'Large', False],['Chani', 'Medium', True],['Depak', 'Medium', False]]
customer_data.remove(False)\
customer_data[2][2] = False
print(customer_data)
我不确定是否有一种方法可以不循环地查看整个列表。通过循环,你可以这样做:
first_names = ['Ainsley', 'Ben', 'Chani', 'Depak']
preferred_size = ['Small', 'Large', 'Medium']
preferred_size.append('Medium')
print(first_names)
print()
print(preferred_size)
print()
customer_data = [['Ainsley', 'Small', True], ['Ben', 'Large', False], ['Chani', 'Medium', True], ['Depak', 'Medium', False]]
for sublist in customer_data: #For each sublist in customer_data
if sublist[2] is False: #If the third element is False
customer_data.remove(sublist) #Remove the sublist
print(customer_data)
for 循环遍历列表中的每个子列表
customer_data
。下一行检查子列表中的第三个元素是否为 False,如果为 False,循环中的第三行将删除子列表。另外,remove
是一个内置的Python函数。