简体   繁体   English

如何将字符串列表转换为整数列表

[英]How to convert a list of strings into a list of integers

In the below part of code v is a list of characters. 在代码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)  

My output looks like 我的输出看起来像

在此处输入图片说明

I want to map all the characters of my input into an integer, so that instead of a table with characters i get a table with numbers. 我想将输入的所有字符映射成一个整数,这样我得到的不是数字表,而是带数字的表。 I tried to use the built in function ord() but it doesnt work, since it only accepts single characters as input and not lists. 我尝试使用内置函数ord(),但它不起作用,因为它仅接受单个字符作为输入,而不接受列表。 Can you help? 你能帮我吗?

If you have a list of letters that you want converting into numbers try: 如果您有要转换为数字的字母列表,请尝试:

>>> [ord(l) for l in letters]
[97, 98, 99, 100, 101, 102, 103]

or 要么

>>> list(map(ord, letters))
[97, 98, 99, 100, 101, 102, 103]

Or if you're dealing with capitalized column headings and want the corresponding index 或者,如果您要处理大写的列标题并想要相应的索引

>>> letters = ['A', 'B', 'C', 'D', 'E']
>>> [ord(l.lower()) -96 for l in letters]
[1, 2, 3, 4, 5]

You can use map() to apply an operation to each item in a list: 您可以使用map()将操作应用于列表中的每个项目:

a = ['a', 'b', 'c']
b = map(lambda c: ord(c), a)

print b
>>> [97, 98, 99]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM