Skills : To be a master at list

list from iteration.

From string

string = 'Hello, Python!'
list(string)
['H', 'e', 'l', 'l', 'o', ',', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!']

From tuple

tup = ('a', 'b', 'c')
tup_packed = 'a', 'b', 'c'

From dictionary

dict = {'key_name':'Austin', 'value_name' : 'student'}

list(dict.items())		# [('key_name', 'Austin'), ('value_name', 'student')]
						# a list of tuple which is composed of key and value from dictionary
                        
list(dict.keys())		# ['key_name', 'value_name']
						# a list of keys from dictionary
                        
list(dict.values())		# ['Austin', 'student']
						# a list of values from dictionary
                        
list_c = list(range(1,10,1))
list_c

From list

List Comprehension

old_list = [1,2,3]
new_list = [i*2 for i in old_list]		# [2, 4, 6]

From map() object

Map()

old_list = ['1', '2', '3']
new_list = list(map(int, old_list))			# [1, 2, 3]

From range() object

list(range(1,11,1))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

From zip() object

list_a = [1,2,3]
list_b = [4,5,6]
tup_a = ('a','b','c')
tup_b = ('d','e','f')

list(zip(list_a, list_b, tup_a, tup_b))

break list

# break list
aaa = [1,2,3]
print(*aaa)
1 2 3

print better way

aaa = [[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,18]]

for i, row in enumerate(aaa):
    print(i)
    print(*row, sep='\n')
    print()
0
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

1
[10, 11, 12]
[13, 14, 15]
[16, 17, 18]

좋은 웹페이지 즐겨찾기