Python 数据类型之 list(讲解+案例+FAQs)
[toc]
FAQs
1. List Comprehension - 双循环
ntest=['a','b']
ltest=[[1,2],[4,5,6]]
data=[(k,v) for k,l in zip(ntest,ltest) for v in l]
https://blog.csdn.net/leavemetomorrow/article/details/90641362
2. 初始化一维数组+二维数组
# 一维数组
a = [None] * n # 方法1
a = [None for i in range(n)] # 方法2
>>> [None, None, None, None, None]
# 二维数组
a = [list()] * 5 # 浅拷贝方法,所有List会同步变化
a[0].append(1) # 方法1
>>> [[1], [1], [1], [1], [1]]
a = [list() for i in range(5)] # 所有List独立
a[0].append(1) # 方法2
>>> [[1], [], [], [], []]
3. TypeError: list indices must be integers or slices, not tuple
问题描述
>>> a=[[1,2,3],[4,5,6]]
>>> a[0] #取一行
[1, 2, 3]
>>> a[:,0] #尝试用数组的方法读取一列失败
TypeError: list indices must be integers or slices, not tuple
产生原因
列表存储不同类型数据,列表元素大小相同或者不同,不支持读取一列
解决方法1:列表解析的方法
>>> b=[x[0] for x in a]
>>> print(b)
解决方法2: 转化为数组直接读取
>>> import numpy as np
>>> a=np.array([[1,2,3],[4,5,6]])
>>> a[:,0]
array([1, 4])
4. IndexError: list assignment index out of range
问题描述
m1=[]
for i in range(10):
m1[i]=1
产生原因
空数组无法直接确定位置,因为内存中尚未分配
**解决方法1:**使用append方法
m1.append(1)
**解决方法2:**先生成一个定长的list
m1=[0]*len(data)
m1[1]=1
5. TypeError: 'list' object is not callable
问题描述
>>> str = "ABCDEF"
>>> list = [1, 2 ,3 ,4 ,5,6 ]
>>> list(str)
TypeError: 'list' object is not callable
产生原因
callable() 是python 的内置函数,用来检查对象是否可被调用
变量list和函数list重名,所以函数在使用list函数时,发现list是一个定义好的列表,而列表是不能把被调用的,因此抛出一个类型错误
6. Python 实现两个列表里元素对应相乘
问题描述
>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list1*list2
TypeError: can't multiply sequence by non-int of type 'list'
解决方法1 : Map函数
List1 = [1,2,3,4]
List2 = [5,6,7,8]
List3 = map(lambda a,b:a*b,zip(List1,List2))
print List3
解决方法2: np.multiply
List1 = [1,2,3]
List2 = [5,6,7]
List3 = np.multiply(np.array(List1),np.array(List2))
print List3.tolist()
7. List 判断空与非空
# 一、二维通用
list = []
if list:
print('非空')
if not list:
print('空')
8. List.append() 输出为None
问题描述
>>> a = []
>>> a = a.append(1)
>>> print(a)
None
产生原因
append 方法不是返回一个列表,而只是修改原来的列表,所以如果用 等式 输出的话,返回是None
解决方法
>>> a = []
>>> a.append(1)
>>> print(a)
1
9. List 合并,判断列表为维数
# 两个列表交叉合并
a=[1,2,3,4,5]
b=[2,3,4,5,6]
c=[]
for x,y in zip(a,b):
c.append([x,y])
print(c)
result : [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
# 二维列表的合并
a=[1,2,3,4,5]
b=[2,3,4,5,6]
c = [a,b]
d = []
for x,y in zip(*c):
d.append([x,y])
print(d)
result : [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]]
#
import numpy as np
a=[0.1,0.2, 0.1, 0.1, 0.1, 0.1]
b=[[0.1, 0.1], [0.2, 0.1], [0.1, 0.1]]
c=[[[0.1,0.5], [0.1,0.8]]]
L1=np.array(a)
print(L1.shape)
print(len(L1.shape))
L=np.array(b)
print(L.shape)
print(len(L.shape))
L2=np.array(c)
print(L2.shape)
print(len(L2.shape))
result :
(6,)
1 # 1维
(3, 2)
2 # 2维
(1, 2, 2)
3 # 3维
10. Float 型列表转化为 Int 型列表
方法1: 使用map方法
>>> list = [1.3, 2.3, 4, 5] #带有float型的列表
>>> int_list = map(int,list) #使用map转换
>>> print int_list
[1, 2, 4, 5]
**方法2:**使用for循环
list1 = [1.3,2.3,4,5]
lista = []
for i in list1:
i =int(i)
lista.append(i)
print lista
[1, 2, 4, 5]
参考文章
Creating a List in Python
Definition:
A list is an ordered set of objects in Python, combine multiple data types in one list.
Benifits:
Key points:
- heights = [61,space 70, 67, 64] # To insert space between two element is recommended
zip(list1,list2)
takes two (or more) lists as inputs and returns an object that contains a list of pairs.
names_and_heights = zip(names, heights)
print(names_and_heights)
because it will return the location of this object in memory. Output would look something like this:
<zip object at 0x7f1631e86b48>
To see the nested lists, you can convert the zip object to a list first:
print(list(names_and_heights))
returns:
[('Jenny', 61), ('Alexus', 70), ('Sam', 67), ('Grace', 65)]
List modifying operation
# add one item to a list
***.append()
def append_sum(lst):
lst.append(lst[-1] + lst[-2])
lst.append(lst[-1] + lst[-2])
lst.append(lst[-1] + lst[-2])
return lst
# Add multiple items to a list
+
gradebook + [("visual arts", 93)]
Range()
my_range = range(10)
>>> print(my_range)
range(0, 10)
>>> print(list(my_range))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
my_range3 = range(1, 100, 10)
before 100 在100之间不包括100
Project 01—Gradebook
last_semester_gradebook = [("politics", 80), ("latin", 96), ("dance", 97), ("architecture", 65)]
subjects = ["physics", "calculus", "poetry", "history"]
grades = [98, 97, 85, 88]
subjects.append("computer science")
grades.append(100)
gradebook=list(zip(subjects, grades))
gradebook + [("visual arts", 93)]
full_gradebook = gradebook + last_semester_gradebook
print (full_gradebook)
Modifying python lists
Definition:
How to work with existing lists of data
Benifits:
Key points:
Get the length of a list len()
Select subsets of a list (called slicing) [ ] [-1] [:]
shopping_list = ['eggs', 'butter', 'milk', 'cucumbers', 'juice', 'cereal']
print(shopping_list[len(shopping_list)-1])
# the last term of list
print(shopping_list[-1])
# 6 not included in the list
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
sublist = letters[1:6]
print(sublist)
['b', 'c', 'd', 'e', 'f']
suitcase = ['shirt', 'shirt', 'pants', 'pants', 'pajamas', 'books']
start = suitcase[:3]
end = suitcase[-2:]
Count the number of times that an element appears in a list letters.count('i')
Sort a list of items ****.sort() sorted()
# sort and sorted have different usuage
# Sort return "none",after sort(),list will change itself
sorted_names = names.sort()
print(sorted_names)
lst.sort()
return lst
# sorted return sorted_list and have no change to original list
sorted_names = sorted(names)
Project 01 — Len's Slice
toppings =['pepperoni', 'pineapple', 'cheese', 'sausage', 'olives','anchovies', 'mushrooms', ]
prices= [2,6,1,3,2,7,2]
num_pizzas = len(toppings)
print ("We sell "+ str(num_pizzas) + " different kinds of pizza!")
pizzas = list(zip(prices, toppings))
pizzas.sort()
print (pizzas)
cheapest_pizza = pizzas[0]
priciest_pizza = pizzas[-1]
print ("I will have your MOST EXPENSIVE pizza!")
three_cheapest = pizzas[:3]
print(three_cheapest)
num_two_dollar_slices=prices.count(2)
print (num_two_dollar_slices)
Project 02 —List Aggregate
# Double index
def double_index(lst,index):
if index <= len(lst)-1:
lst[index]=lst[index]*2
return lst
else:
return lst
print(double_index([3, 8, -10, 12], 2))
# Remove middle
def remove_middle(lst, start, end):
lst=lst[:start]+lst[end+1:]
return lst
print(remove_middle([4, 8, 15, 16, 23, 42], 1, 3))
#More than N
def more_than_n (lst, item, n):
if lst.count(item)>n:
return True
else:
return False
print(more_than_n([2, 4, 6, 2, 3, 2, 1, 2], 2, 3))
# More Frequent Item
def more_frequent_item (lst,item1,item2):
if lst.count(item1) >= lst.count(item2):
return item1
else:
return item2
print(more_frequent_item([2, 3, 3, 2, 3, 2, 3, 2, 3], 2, 3))
# Middle Item
def middle_element(lst):
if len(lst) % 2 == 0:
sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]
return sum / 2
else:
return lst[int(len(lst)/2)]
print(middle_element([5, 2, -10, -4, 4, 5]))
Summary
ADD
list.append(data)
list1.extend(list2)
liat1.insert(index,data)
MODIFY
list[index] = data
DEL
del list[index] # unrecommended
list.remove[data] Delete specified element of first appearance in the list
list.pop() delete the final one element
list.pop(index) delete element at specific location
list.clear delete the whole of list
Aggeregate function
list.count(data)
len(list)
Sort
list.sort(reverse = true) descending sort
list.reverse() reverse the order
sorted()