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

  

列表

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

  

1
2
3
4
5
列表变成字典<br>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}

  

字典

1
2
3
字典变成字符串<br>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   黑逍逍  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!



点击右上角即可分享
微信分享提示