如何将string列表转换为整数列表
在下面的代码部分v是一个字符的列表。
import collections import csv import sys with open("prom output.csv","r") as f: cr = csv.reader(f,delimiter=",") d=collections.defaultdict(lambda : list()) header=next(cr) for r in cr: d[r[0]].append(r[1]) with open("sorted output.csv","w") as f: cr = csv.writer(f,sys.stdout, lineterminator='\n') od = collections.OrderedDict(sorted(d.items())) for k,v in od.items(): cr.writerow(v)
我的输出看起来像
我想将我的input的所有字符映射到一个整数,所以,而不是一个表与字符我得到一个数字表。 我试图使用内置的函数ord(),但它不工作,因为它只接受单个字符作为input,而不是列表。 你能帮我吗?
如果你有一个你想要转换成数字的字母列表,请尝试:
>>> [ord(l) for l in letters] [97, 98, 99, 100, 101, 102, 103]
要么
>>> list(map(ord, letters)) [97, 98, 99, 100, 101, 102, 103]
或者如果你正在处理大写的列标题,并希望相应的索引
>>> letters = ['A', 'B', 'C', 'D', 'E'] >>> [ord(l.lower()) -96 for l in letters] [1, 2, 3, 4, 5]
您可以使用map()
将操作应用于列表中的每个项目:
a = ['a', 'b', 'c'] b = map(lambda c: ord(c), a) print b >>> [97, 98, 99]