xiaofan1228 发表于 2020-3-15 19:21:07

【零基础向】关于列表的几个有趣的知识

本帖最后由 xiaofan1228 于 2020-3-15 20:15 编辑

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 =
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 =
L2 =
remove_dups(L1, L2)
print(L1)
# 在第一次for 循环中 L1 = 1被删除,此时L1 = , 然后索引直接进入L1 = 3,跳过了L = 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 =
L4 =
remove_dups_1(L3, L4)
print(L3)
#
页: [1]
查看完整版本: 【零基础向】关于列表的几个有趣的知识