split():將字串轉換為列表,並以逗號分隔。
join():它將列表轉換為字串。
例:
1。反轉給定的輸入-->星期四是今天
方法:1 使用循環
s = "today is thursday" reverse = "" i = 0 while i<len(s): reverse = reverse + s[-(i+1)] i+=1 print(reverse) #yadsruht si yadot i = 0 word = "" while i<len(reverse): if reverse[i]==' ': print(word[::-1],end=' ') word = "" i+=1 continue word = word + reverse[i] i+=1 else: print(word[::-1])
方法:2 使用清單
sen = "today is thursday" l = sen.split(" ") print(l) print(l[::-1]) s = " ".join(l[::-1]) print(s)
輸出:
yadsruht si yadot thursday is today
深拷貝:
-->在 Python 中,指派給可變物件(如列表)的變數會保存對物件的參考。
-->如果兩個變數引用同一個對象,則透過一個變數所做的變更將反映在另一個變數中。
範例:
l1 = [10,20,30] l2 = l1 print(l1) print(id(l1)) print(l2) print(id(l2)) l2[0] = 111 print(l1) print(l2)
輸出:
[10, 20, 30] 127285488814912 [10, 20, 30] 127285488814912 [111, 20, 30] [111, 20, 30]
淺複製:
--> copy() 方法建立一個新的列表對象,但僅複製元素的參考(對於嵌套對象)。
-->它將儲存在單獨的記憶體位址中。
範例:
l1 = [10,20,30] l2 = l1.copy() print(l1) print(id(l1)) print(l2) print(id(l2)) l2[0] = 111 print(l1) print(l2)
輸出:
[10, 20, 30] 140500496468800 [10, 20, 30] 140500496470528 [10, 20, 30] [111, 20, 30]
字典順序:
-->字典順序是指根據字母的字母順序按字典順序排列它們。
-->按 ASCII 順序比較。 (A-Z:65-91),(a-z:97-122)
使用比較運算子:
l1 = ['lakshmi', 'guru', 'kuhan'] l2 = ['lakshmi', 'guru', 'kuhan'] print(l1 == l2) print(l1 != l2) l2 = ['guru', 'lakshmi', 'kuhan'] print(l1>l2) print(l1<l2)
輸出:
True False True False
練習:面試問題
l1 = [10,20,30] l2 = [5,6,7] for no in l1: for num in l2: print(no, num, end=' ') print()
輸出:
10 5 10 6 10 7 20 5 20 6 20 7 30 5 30 6 30 7
l1 = [10,20,30] l2 = [8,20,7] for no in l1: for num in l2: if no != num: print(no, num,end=' ') print()
輸出:
10 8 10 20 10 7 20 8 20 7 30 8 30 20 30 7
任務:
1.從清單中找出總和為:5
的對
l1 = [1,2,3,4,5,6,7,8,9,0]
方法:1
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] pairs = [] for i in l: for j in l: if i + j == 5: pairs.append((i,j)) print(pairs)
輸出:
[(1, 4), (2, 3), (3, 2), (4, 1), (5, 0), (0, 5)]
方法:2
l = [1,2,3,4,5,6,7,8,9,0] for i in range(len(l)): for j in range(len(l)): sum = l[i] + l[j] if sum == 5: print(l[i], l[j])
輸出:
1 4 2 3 3 2 4 1 5 0 0 5
2。找出缺少的號碼
l = [10,20,30,50,60,70,80,90]
方法:1
l = [10, 20, 30, 50, 60, 70, 80, 90] results = [] for i in range(len(l) - 1): if l[i + 1] - l[i] != 10: results.append(int((l[i] + l[i + 1]) / 2)) for result in results: print(result)
方法:2
l = [10,20,30,50,60,70,80,90] i=0 while i<len(l)-1: if l[i+1]-l[i]!=10: result=(l[i]+l[i+1])/2 print(int(result)) i+=1
輸出:
40
以上是Python 日期列表函數、任務的詳細內容。更多資訊請關注PHP中文網其他相關文章!