《Python for Beginners》为LearnStreet上的Python入门课程。本节主要学习内容为Lists and Tuples。
Lesson 6 Lists and Tuples
1. Length of List
计算List变量的长度。
1 def run(var): 2 #return your code here 3 return len(var) 4 5 #This is just for you to see what happens when the function is called 6 print run([1,2,3,4,5])
输出结果:
5
2. Removing Elements of a List
移除列表中的某个元素。
days = ["funday","sunday","monday","tuesday","wednesday","thursday","friday"]
days.pop(0)
注意:pop(0)使用的是圆括号。
3. Appending Lists
在列表末尾添加元素。
days.append("saturday")
其中,days为List类型变量。
4. Concatenating Lists
连接两个列表。
1 def run(first, second): 2 #your code here 3 return first + second 4 5 #This is just for you to see what happens when the function is called 6 print run([1,2,3],[4,5,6])
输出结果:
[1, 2, 3, 4, 5, 6]
5. Tuples
创建tuple变量使用圆括号而不是方括号,tuple类型的变量值是不可变的。
例如:tup = (10, 20, 30)
1 def run(): 2 #your code here 3 name = ("Guinevere", 9102) 4 return name 5 6 #This is just for you to see what happens when the function is called 7 print run()
输出结果:
('Guinevere', 9102)
6. 复习练习
1 # assume lst is a list and tup is a tuple 2 def run(lst, tup): 3 #your code here 4 if lst[1] == tup[1]: 5 return tuple(lst) == tup 6 else: 7 return "not equal" 8 9 #This is just for you to see what happens when the function is called 10 print run([1,2,3],(1,2,3))
输出结果:
True
注意:类型转换tuple(lst)
总结:
tuple和list是两种不同的数据类型,他们永远不会相等。但是他们内部的元素都是string类型,可以进行比较。