li = [1,2,3,4,12,2,1,3,5,6,7,8,19,20,12,43,1314]
# 1. 原始遍历去重
new_li = []
for i in li:
if i not in new_li:
new_li.append(i)
# 2. 利用set特性去重,最便捷的方式
new_li_set = list(set(li))
# 3. 利用字典的key唯一特性去重
new_li_dict = list({}.fromkeys(li).keys())
print(new_li)
print(new_li_set)
print(new_li_dict)
[1, 2, 3, 4, 12, 5, 6, 7, 8, 19, 20, 43, 1314]
[1, 2, 3, 4, 5, 6, 7, 8, 1314, 43, 12, 19, 20]
[1, 2, 3, 4, 12, 5, 6, 7, 8, 19, 20, 43, 1314]
# 1. 首先我们要下说明,不能删除的原因. 删除元素后导致元素的索引发生变化。后的元组自动向前移动了
# 1. 利用while 循环删除
li = [1,2,2,3,3,4,4,5,6,8,8]
li_copy = li1.copy()
index=0
while index<len(li):
if li[index]%2==0:
li.remove(li[index])
continue
index+=1
print(li)
# 2. 保留奇数数值
new_li = [i for i in li_copy if i%2!=0]
print(new_li)
# 3.利用切片特性,切片等价于做了一个浅拷贝。这样遍历与删除就不是同一个列表
li1 = [1,2,2,3,3,4,4,5,6,8,8]
for i in li1[::]:
if i%2==0:
li1.remove(i)
print(li1)
# 4. 可以保留偶数在删除与上面类似
li3 = [1,2,2,3,3,4,4,5,6,8,8]
new_li3 = [i for i in li3 if i % 2==0]
for i in new_li3:
li3.remove(i)
print(li3)
[1, 3, 3, 5]
[1, 3, 3, 5]
[1, 3, 3, 5]
[1, 3, 3, 5]
li = [1,2,3]
li1 = li
li2=li[::]
li3 = li.copy()
下面是源代码示例
def reduce(function, sequence, initial=_initial_missing):
"""
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
"""
it = iter(sequence)
if initial is _initial_missing:
try:
value = next(it)
except StopIteration:
raise TypeError("reduce() of empty sequence with no initial value") from None
else:
value = initial
for element in it:
value = function(value, element)
return value
# 1. 利用切片的反向切片操作
s = "abcdefg"
s1 = s[::-1]
print(s1)
# 2. 利用list的逆置与字符串拼接
li = list(s)
li.reverse()
s2 = "".join(li)
print(s2)
# 3. 传统的字符串遍历
s3 = ""
for ts in s:
s3 = ts+s3
print(s3)
gfedcba
gfedcba
gfedcba
# 利用遍历的多变量赋值操作哈
a = 10
b = 20
b,a = a,b
print(a,b)
20 10