Adriano10 Adriano10 - 1 month ago 4x
Python Question

How to convert a list of strings into a list of integers

In the below part of code v is a list of characters.

import collections
import csv
import sys

with open("prom output.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())

for r in cr:

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():

My output looks like

enter image description here

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. 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]


>>> 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]