python中的列表与数组转换

Python012

python中的列表与数组转换,第1张

列表转换成数组或者数组转换成列表,操作如下(使用函数array 和 tolist):

from numpy import *

listS = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [20, 30, 40, 50, 60, 70, 80, 90, 100]]

print(listS)

temp_array = array(listS, dtype=object)

print(temp_array)

listR = temp_array.tolist()

print(listR)

>>>b

['efggt', 'ssss', 'aege22']

>>>c = sort(b)

>>>c

array(['aege22', 'efggt', 'ssss'],

dtype='|S6')

>>>c = list(sort(b))

>>>c

['aege22', 'efggt', 'ssss']

可以用字典来处理,trans 当key处理,后面的item放到列表里。示例如下:

sss = '''trans1=item1

trans2=item1

trans2=item2'''

result_dict = {}

for s in sss.split("\n"):

    key = s.split("=")[0]

    value = s.split("=")[1]

    if not result_dict.has_key(key):

        result_dict[key] = []

    result_dict[key].append(value)

    

print result_dict