鱼C论坛

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

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

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

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

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

x
本帖最后由 xiaofan1228 于 2020-3-15 20:15 编辑
  1. s = "Sophie and Jimmy"
  2. print(list(s))
  3. # ['S', 'o', 'p', 'h', 'i', 'e', ' ', 'a', 'n', 'd', ' ', 'J', 'i', 'm', 'm', 'y']
  4. print(s.split(" "))
  5. # ['Sophie', 'and', 'Jimmy']
  6. L = "love"
  7. l = list(L)
  8. print(''.join(l))
  9. # love
  10. print("_".join(l))
  11. # l_o_v_e
  12. print(s.join(l))
  13. # lSophie and JimmyoSophie and JimmyvSophie and Jimmye

  14. # append 的弊端 side effects:赋值语句不能拷贝列表,而是增加了列表对象的指针

  15. warm = ["red", "yellow", "orange"]
  16. hot = warm
  17. hot.append("pink")
  18. print(hot)
  19. print(warm)
  20. # ['red', 'yellow', 'orange', 'pink']
  21. # ['red', 'yellow', 'orange', 'pink']

  22. # 这种情况可以被继承

  23. warm = ["red", "yellow", "orange"]
  24. hot = ["red"]
  25. brightcolors = [warm]
  26. brightcolors.append(hot)
  27. print(brightcolors)
  28. hot.append("pink")
  29. print(hot)
  30. print(brightcolors)


  31. # [['red', 'yellow', 'orange'], ['red']]
  32. # ['red', 'pink']
  33. # [['red', 'yellow', 'orange'], ['red', 'pink']]

  34. # 迭代过程中index counter并不会随着列表的改变而改变

  35. def remove_dups(L1, L2):
  36.     for e in L1:
  37.         if e in L2:
  38.             L1.remove(e)


  39. L1 = [1, 2, 3, 4]
  40. L2 = [1, 2, 5, 6]
  41. remove_dups(L1, L2)
  42. print(L1)
  43. # [2, 3, 4] 在第一次for 循环中 L1[0] = 1被删除,此时L1 = [2,3,4], 然后索引直接进入L1[1] = 3,跳过了L[0] = 2
  44. # 如果想维持或拷贝原列表,可以采用切片方式

  45. cool = ["blue", "green", "grey"]
  46. chill = cool[:]
  47. chill.append("black")
  48. print(chill)
  49. print(cool)
  50. # ['blue', 'green', 'grey', 'black']
  51. # ['blue', 'green', 'grey']

  52. def remove_dups_1(L1, L2):
  53.     L1_copy = L1[:]
  54.     for e in L1_copy:
  55.         if e in L2:
  56.             L1.remove(e)


  57. L3 = [1, 2, 3, 4]
  58. L4 = [1, 2, 5, 6]
  59. remove_dups_1(L3, L4)
  60. print(L3)
  61. # [3, 4]
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-5-1 04:53

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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