2017年9月7日 星期四

Python - Building a list using for loop and other work about list - list用迴圈產生、list串接(相加)、使用迴圈切割list

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)

System version :Windows 10
list1 = ['a'+str(x) for x in range(7)]
print(list1)
print('='*40)

list2=[]
for a in range(2):
    list2=list2+list1
print(list2)
print('='*40)

num = 3
for a in range(0,len(list2),num):
    print(list2[a:a+num])
執行結果:
['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6']
========================================
['a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6']
========================================
['a0', 'a1', 'a2']
['a3', 'a4', 'a5']
['a6', 'a0', 'a1']
['a2', 'a3', 'a4']
['a5', 'a6']

2017年9月5日 星期二

Python - Convert String to list and Convert list to dictionary in Python - 字串藉由指定符號轉為list與list轉為字典

Python version :Python 3.6.0 :: Anaconda 4.3.1 (64-bit)
System version :Windows 10
str1 = '背景,0,特性,1,元件,3'
list1 = str1.split(",")
dic1 = {list1[i]: list1[i+1] for i in range(0, len(list1), 2)}
print(list1)
print(dic1)
執行結果:
['背景', '0', '特性', '1', '元件', '3']
{'背景': '0', '特性': '1', '元件': '3'}