[expression for item in iterable if condition]
  • expression 是对 item 的操作或处理,它的结果会成为新列表的元素。
  • itemiterable 中的对象。
  • iterable 是一个可以遍历的对象,比如列表、字典、集合、字符串等。
  • if condition 是一个可选的条件语句,用于筛选符合条件的元素

  

列表

列表操作列表
nums = [1, 2, 3, 4, 5, 6] even_squares = [n**2 for n in nums if n % 2 == 0] # even_squares: [4, 16, 36]

  

列表变成字典
students = ['Alice', 'Bob', 'Charlie'] scores = [85, 88, 90] student_scores = {student: score for student, score in zip(students, scores)} print(student_scores) # {'Alice': 85, 'Bob': 88, 'Charlie': 90}

  

字典

字典变成字符串
my_dict = {'a':1, 'b':2, 'c':3} formatted_str = '; '.join([f'{key}:{value}' for key, value in my_dict.items()]) print(formatted_str) # 输出: "a:1; b:2; c:3"

  

 

posted on 2023-12-29 17:04  黑逍逍  阅读(2)  评论(0编辑  收藏  举报