Python 语法练习题
001、strings=["a","as","bat","car","dove","python"] 过滤掉长度小于等于2的字符串,并将剩下的字符串转换成大写字母形式。
方法一:
strings=["a","as","bat","car","dove","python"]
y = filter(lambda string: len(string) > 2, strings)
list(map(lambda s: s.upper(), y))
# [i.upper() for i in y]
方法二:
strings=["a","as","bat","car","dove","python"]
[i.upper() for i in y]
002、 strings=["a","as","bat","car","dove","python"] 创建一个指向列表位置的映射关系的字典。
方法一:
strings=["a","as","bat","car","dove","python"]
dic = {}
for i in range(len(strings)):
dic[i] = strings[i]
dic
方法二:
strings=["a","as","bat","car","dove","python"]
dic = {}
for i, s in enumerate(strings):
dic[i] = s
dic
方法三:
strings=["a","as","bat","car","dove","python"]
dict((k, v) for k, v in enumerate(strings))
方法四:
strings=["a","as","bat","car","dove","python"]
{i: s for i, s in enumerate(strings)}
003、some_tuples=[(1,2,3),(4,5,6),(7,8,9)] 将这个整数元组构成的列表成为一个简单的整数列表。
方法一:
some_tuples=[(1,2,3),(4,5,6),(7,8,9)]
lst = []
for tup in some_tuples:
for num in tup:
lst.append(num)
lst
方法二:
some_tuples=[(1,2,3),(4,5,6),(7,8,9)]
[num for tup in some_tuples for num in tup ]
004、all_data=[["Tom","Billy","Jefferson","Andrew","Wesley","Steven","Joe"], ["Susie","Casey","Jill","Ana","Eva","Jennifer","Stephanie"]]我们要找出带有2个或以上的字母e的名字,并将它们放入一个新列表.
方法一:
all_data=[["Tom","Billy","Jefferson","Andrew","Wesley","Steven","Joe"],
["Susie","Casey","Jill","Ana","Eva","Jennifer","Stephanie"]]
[s for lst in all_data for s in lst if s.count('e') >= 2]
非学无以广才,非志无以成学。