Python grammar exercises

001, strings = [ "a", "as", "bat", "car", "dove", "python"] was filtered off equal to the string length is less than 2, and the remaining string to uppercase form.

method one:

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]

Method Two:

strings=["a","as","bat","car","dove","python"] 

[i.upper() for i in y]

 

002, strings = [ "a", "as", "bat", "car", "dove", "python"] create a dictionary mapping relationship list of locations of points.

method one:

strings=["a","as","bat","car","dove","python"] dic = {} for i in range(len(strings)): dic[i] = strings[i] dic

Method Two:

strings=["a","as","bat","car","dove","python"]

dic = {}
for i, s in enumerate(strings):
    dic[i] = s
    
dic

 

Method three:

strings=["a","as","bat","car","dove","python"] dict((k, v) for k, v in enumerate(strings))

Method four:

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)] The list of tuples this integer becomes a simple list of integers.

method one:

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

Method Two:

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 "]] we want to find out the name with two or more letters e, and put a new list them.

method one:

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]

Guess you like

Origin www.cnblogs.com/shanger/p/12180789.html