miik
miik

Reputation: 663

list being printed out weirdly python

I have a list like this

[796, 829, 1159, 1162]

I also have a list like this:

['144 154', '145 151', '145 152', '145 153', '145 154', '146 152', '146 153', '146 154', '147 153', '147 154'] These are not to scale

What I want to do is use the first lists elements as index for the last array

I have tried this piece of code:

contacts = []
for i in findres:
    contacts += rulelines[i]
print contacts

where findres is the first list and rulelines is the last list However this prints the contacts list out weirdly:

['5', ' ', '7', '2', '5', ' ', '1', '0', '5', '7', ' ', '1', '5', '0', '7', ' ', '1', '5', '3']

I'm sure its easy but where am I going wrong??

The desirable output I believe is ['5 72','5 105', '7 150',7 153']

I have not put down all of the list elements as there are over 100 elements in each

Upvotes: 0

Views: 97

Answers (3)

Thanakron Tandavas
Thanakron Tandavas

Reputation: 5683

If I understand correctly, you need to extract the first number in every elements of findres first. Then, use those extracted numbers as an index for another array

>>> findres = ['144 154', '145 151', '145 152', '145 153', '145 154', '146 152', '146 153', '146 154', '147 153', '147 154']
>>> first_elements = [c.split()[0] for c in findres]
>>> print first_elements 

['144', '145', '145', '145', '145', '146', '146', '146', '147', '147']

>>> contact = []
>>> for i in first_elements:
        contacts.append(rulelines[i])

Upvotes: 0

daedalus
daedalus

Reputation: 10923

Use this as a template:

findres = [5, 7, 15, 22]
contacts = list('abcdefghijklmnopqrstuvwxyz') # dummy list

result = [ contacts[index] for index in findres ]
print result

# ['f', 'h', 'p', 'w']

Upvotes: 1

mariano
mariano

Reputation: 1367

Looks like when you assign contacts = rulelines[i] you're actually assigning the rulelines[i] string. You should do contacts.append(rulelines[i]) to add the the contact to the list, otherwise you're constantly overwriting over the last assignment.

Upvotes: 2

Related Questions