Nico
Nico

Reputation: 1

Python List Separation

I am trying to separate a list that is made up of a series of two strings:

(e.g. ['9434e user1', '8434f user2'] and so on).

I am trying to make a list for the hash values and a list for the usernames.

I tried

for x in range(len(list)): 
    newList.append(list[:5])

in an attempt to get a list of the hash values, but I'm just getting a list made up of one item, that item being the entire original list.

What's the best way to get the two separate parts in two different lists in python?

Upvotes: 0

Views: 65

Answers (2)

dslack
dslack

Reputation: 845

Here are two options:

strings = ['9434e user1', '8434f user2']
hashes = []
users = []
for string in strings:
    this_hash = string.split()[0]
    this_user = string.split()[1]
    hashes.append(this_hash)
    users.append(this_user)

or

hashes2 = [string.split()[0] for string in strings]
users2 = [string.split()[1] for string in strings]

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304205

>>> hsh, names = zip(*(x.split() for x in ['9434e user1', '8434f user2']))
>>> hsh
('9434e', '8434f')
>>> names
('user1', 'user2')

Explanation: This part just splits the items up

>>> [x.split() for x in ['9434e user1', '8434f user2']]
[['9434e', 'user1'], ['8434f', 'user2']]

Now there is a nice idiom to transpose this list of lists

zip(*foo) # transposes foo

Upvotes: 2

Related Questions