Python 常用的原生函数

本文介绍了如何使用Python列表进行初始化、增删元素,以及通过for循环、列表推导式、filter()、all()、some()等函数实现高效操作。特别关注了如何提取字符串首字母并创建新列表,以及利用map()和类似函数进行列表处理。
摘要由CSDN通过智能技术生成
List Object basic
# Initialization
L = [‘Alpha’, ‘Beta’, ‘Gamma’]
# Append new item
L.append(‘Delta’)
# Remove item by index
L.pop(idx)
# Remove item by value
L.remove(‘Alpha’)

Walk through list items

# The code below can not be stupid more
for i in range(len(L)):
    print(L[i])

# Typical for loop
for item in L:
    print(item)

# Would like to have index as well
for idx, item in enumerate(L):
    print(“{0}: {1}”.format(idx, item))

List comprehension

# Would like to extract 1st letter of each item inside and make a new list
# Regular for loop
L2 = []
for item in L:
    L2.append(L[0])

# List Comprehension
L2 = [x[0] for x in L]

# Use primitive function ‘map’ instead
L2 = map(lambda x: x[0], L)

Similar primitive function beside 'map'

# Keep the item if internal function output True, otherwise drop the item. Notice that function filter return a list which filter out unsatisfied items and leave other items unchanged.
filter(lambda x: …, L)

# Output True only if internal function return True for each item
all(lambda x: …, L)

# Output True if any of the internal function return True
some(lambda x: …, L)

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值