s = "Sophie and Jimmy"
print(list(s))
# ['S', 'o', 'p', 'h', 'i', 'e', ' ', 'a', 'n', 'd', ' ', 'J', 'i', 'm', 'm', 'y']
print(s.split(" "))
# ['Sophie', 'and', 'Jimmy']
L = "love"
l = list(L)
print(''.join(l))
# love
print("_".join(l))
# l_o_v_e
print(s.join(l))
# lSophie and JimmyoSophie and JimmyvSophie and Jimmye
# append 的弊端 side effects:赋值语句不能拷贝列表,而是增加了列表对象的指针
warm = ["red", "yellow", "orange"]
hot = warm
hot.append("pink")
print(hot)
print(warm)
# ['red', 'yellow', 'orange', 'pink']
# ['red', 'yellow', 'orange', 'pink']
# 这种情况可以被继承
warm = ["red", "yellow", "orange"]
hot = ["red"]
brightcolors = [warm]
brightcolors.append(hot)
print(brightcolors)
hot.append("pink")
print(hot)
print(brightcolors)
# [['red', 'yellow', 'orange'], ['red']]
# ['red', 'pink']
# [['red', 'yellow', 'orange'], ['red', 'pink']]
# 迭代过程中index counter并不会随着列表的改变而改变
def remove_dups(L1, L2):
for e in L1:
if e in L2:
L1.remove(e)
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
remove_dups(L1, L2)
print(L1)
# [2, 3, 4] 在第一次for 循环中 L1[0] = 1被删除,此时L1 = [2,3,4], 然后索引直接进入L1[1] = 3,跳过了L[0] = 2
# 如果想维持或拷贝原列表,可以采用切片方式
cool = ["blue", "green", "grey"]
chill = cool[:]
chill.append("black")
print(chill)
print(cool)
# ['blue', 'green', 'grey', 'black']
# ['blue', 'green', 'grey']
def remove_dups_1(L1, L2):
L1_copy = L1[:]
for e in L1_copy:
if e in L2:
L1.remove(e)
L3 = [1, 2, 3, 4]
L4 = [1, 2, 5, 6]
remove_dups_1(L3, L4)
print(L3)
# [3, 4]