鱼C论坛

 找回密码
 立即注册
查看: 2886|回复: 0

[学习笔记] 【零基础向】关于列表的几个有趣的知识

[复制链接]
发表于 2020-3-15 19:21:07 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 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 = [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]
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-3-14 21:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表