一个包含两维的list,是可以直接转为dictionary的key-value格式,比如下例:
>>> lists = ([('sape', 4139), ('guido', 4127), ('jack', 4098)])
>>> dict(lists)
{'sape': 4139, 'guido': 4127, 'jack': 4098}
如果是一个dict,使用list直接将dict中的key值转为list格式:
>>> dicts = {'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> list(dicts)
['sape', 'guido', 'jack']
若有两个列表list,合并为一个dict,其中一个列表的值为key,另一个列表的值为value:
>>> list1
['sape', 'guido', 'jack']
>>> list2
['4139', '4127', '4098']
>>> zip(list1,list2)
>>> dict(zip(list1,list2))
{'sape': '4139', 'guido': '4127', 'jack': '4098'}
>>> list1
['sape', 'guido', 'jack']
>>> list2
['4139', '4127', '4098']
>>> merge = zip(list1,list2)
>>> merge
>>> for a,b in merge:
print(a,b)
sape 4139
guido 4127
jack 4098
>>> dict(zip(list1,list2))
{'sape': '4139', 'guido': '4127', 'jack': '4098'}
- 合并到一个DataFrame里面:
- 方法一
- 先将两个列表合并成一个dict;
- dict传入DataFrame
- 方法二
- 直接创建(一个列表中含有多个子列表,也可直接创建)
#方法一
>>> list1
['sape', 'guido', 'jack']
>>> list2
['4139', '4127', '4098']
>>> dict1 = {'list1':list1,'list2':list2}
>>> import pandas
>>> data = DataFrame(dict1)
Traceback (most recent call last):
File "", line 1, in
data = DataFrame(dict1)
NameError: name 'DataFrame' is not defined
>>> data = pandas.DataFrame(dict1)
>>> data
list1 list2
0 sape 4139
1 guido 4127
2 jack 4098
#方法二
>>> pandas.DataFrame([list1,list2],index=['list1','list2'])
0 1 2
list1 sape guido jack
list2 4139 4127 4098
list里面是tuple:
>>> lists
[('尚撷福最近很忙', 'Geoffrey has been busy lately.'), ('就拿今天说吧', 'Take today for example.'), ('他不仅要跟全家人一起包饺子', 'He’s going to make dumplings with his family')]
>>> lists_ = [list(x) for x in lists]
>>> lists_
[['尚撷福最近很忙', 'Geoffrey has been busy lately.'], ['就拿今天说吧', 'Take today for example.'], ['他不仅要跟全家人一起包饺子', 'He’s going to make dumplings with his family']]