我有清单
['Q 0006 005C 0078 0030 0030 0033 0034 ONE_OF 0002 ']
如何删除第一个元素Q
和0002
最后一个元素?
如果您的列表存储在下面,my_list
那么这应该可以。
my_list = my_list[1:-1]
我不确定您到底想要什么,因为目前还不清楚,但这应该会有所帮助。实际上,该列表中只有一个元素。
假设您的所有列表项都是以空格作为分隔符的字符串,以下是如何从列表中的每个字符串中删除第一组和最后一组字符的方法。
>>> L = ['Q 0006 005C 0078 0030 0030 0033 0034 ONE_OF 0002 ']
>>> [' '.join(el.split()[1:-1]) for el in L]
['0006 005C 0078 0030 0030 0033 0034 ONE_OF']
另一种(相当 Pythonic)的方法是使用扩展序列解包功能:
my_list = _ , *my_list, _
例子
>>> my_list = [1, 2, 3, 4, 5]
>>> _, *my_list, _ = my_list
>>> my_list
[2, 3, 4]
#initialize 2 lists what will hold your integers
List1 = []
List2 = []
# prompt the user to enter the integers in the list
List1 = eval(input("Enter the list of integers:")
#Iterate over the list to remove the first and last integer
for i in range(len(List1):
List2 = list1[1:-1]
#print the contents of your new list to verify the results
print(List2) # the output shouldn't contain first and last integer of List1
# prompt the user to enter the integers in the list
List1 = eval(input("Enter the list of integers:")
#Iterate over the list to remove the first and last integer
for i in range(len(List1):
List2 = list1[1:-1]
#print the contents of your new list to verify the results
print(List2) # the output shouldn't contain first and last integer of List1