python基础之列表的坑
#列表的坑之一 list1 = ['python','java','php','c','c++','c#','ruby'] #将索引为奇数的元素删除 ['java','c','c#'] list2 = [] for item in list1: if list1.index(item) % 2 != 1: list2.pop(list1.index(item)) print(list1) # ['python', 'php', 'c', 'c#', 'ruby'] #这是因为列表用pop之后,后面的索引都会自动减一 #切片 list1 = ['python','java','php','c','c++','c#','ruby'] list2 = list1[1::2] print(list2) #['java','c','c#'] #赋值到其他的空列表 list1 = ['python','java','php','c','c++','c#','ruby'] list2 = [] for i in list1: if list.index(i)%2==0: list2.append(i) print(list2) # ['java','c','c#'] #倒序删除 list1 = ['python','java','php','c','c++','c#','ruby'] for i in range(len(list1)-1,-1,-1): if i % 2 == 0: del li[i] print(list1) # ['java','c','c#']