name_list = ["刘备", "张飞", "刘备", "诸葛亮"]
temp_list = []
for name in name_list:
# 判断name是否在temp_list中
# 判断name是否是temp_list的成员
# 如果是成员,不保存。否则才保存
if name not in temp_list:
temp_list.append(name)
print(temp_list)
通过索引判断
方式一,利用枚举
name_list = ["刘备", "张飞", "刘备", "诸葛亮"]
temp_list = []
for i,name in enumerate(name_list):
print(name, name_list.index(name),i)
if name_list.index(name) == i:
temp_list.append(name)
print(temp_list)
方式二,无枚举,自己造下标
name_list = ["刘备", "张飞", "刘备", "诸葛亮"]
# name_list.index("刘备")
temp_list = []
num_len = len(name_list) # 4
for i in range(num_len): # for i in range(0,4)
# print(i)
# 列表[下标]
name = name_list[i]
print(name,i)
firse_show_index = name_list.index(name) # 下标 = 列表.index(成员)
if i == firse_show_index:
temp_list.append(name)
print(temp_list)
方法三新数据类型
name_list = ["刘备", "张飞", "刘备", "诸葛亮"]
s = list(set(name_list))
print(s, type(s))
set数据类型
特点是,无重复
创建集合,强转集合
集合对象 = set(列表或元组)