Amar
Amar

Reputation: 90

I need to remove single inverted commas from list

When I open contestant file, I'm getting below output and below list is having single inverted comma in all indexes, because of that I'm facing issue.

output

:
[['1951', '1874'], ['1957', '1519'], ['1962', '1985'], ['1967', '2369'], ['1971', '2784'], ['1977', '2439']]

I need the list like below. please let me know, what i need to do?

year = [1951,1957,1962,1967,1971,1977]
contest = [1874,1519,1985,2369,2784,2439]

Upvotes: 0

Views: 687

Answers (4)

user9158931
user9158931

Reputation:

Why two loops , you can do in one loop :

data=[['1951', '1874'], ['1957', '1519'], ['1962', '1985'], ['1967', '2369'], ['1971', '2784'], ['1977', '2439']]

year=[]
contenst=[]

for i in data:
    year.append(int(i[0]))
    contenst.append(int(i[1]))

print(year)
print(contenst)

output:

[1951, 1957, 1962, 1967, 1971, 1977]
[1874, 1519, 1985, 2369, 2784, 2439]

Upvotes: 1

RoadRunner
RoadRunner

Reputation: 26315

You can zip() your lists together into tuples of str:

>>> l = [['1951', '1874'], ['1957', '1519'], ['1962', '1985'], ['1967', '2369'], ['1971', '2784'], ['1977', '2439']]
>>> year, contest = zip(*l)
>>> year
('1951', '1957', '1962', '1967', '1971', '1977')
>>> contest
('1874', '1519', '1985', '2369', '2784', '2439')

Then you can map() them to int:

>>> list(map(int, year))
[1951, 1957, 1962, 1967, 1971, 1977]
>>> list(map(int, contest))
[1874, 1519, 1985, 2369, 2784, 2439]

Note: Since map() returns a generator, you need to wrap list() to convert it to a list. The other option is to use a list comprehension: [int(x) for x in lst].

Upvotes: 4

Roushan
Roushan

Reputation: 4420

data =[['1951', '1874'], ['1957', '1519'], ['1962', '1985'], ['1967', '2369'], ['1971', '2784'], ['1977', '2439']]
year=[int(x[0])  for x in data]#=>[1951, 1957, 1962, 1967, 1971, 1977]
contest=[int(x[1])  for x in data]#=>[1874, 1519, 1985, 2369, 2784, 2439]

Upvotes: 2

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

For the first list:

year=[int(i[0]) for i in [['1951', '1874'], ['1957', '1519'], ['1962', '1985'], ['1967', '2369'], ['1971', '2784'], ['1977', '2439']]]

For the second list

contest=[int(i[1]) for i in [['1951', '1874'], ['1957', '1519'], ['1962', '1985'], ['1967', '2369'], ['1971', '2784'], ['1977', '2439']]]

Upvotes: 2

Related Questions