user2180683
user2180683

Reputation: 219

Create new tuple from an existing one while changing one of its elements?

I'm at a point where I have a list of tuples like this:

[('Ben', '5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5'),
 ('Moose', '5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 -3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0'),
  ...]

it continues on for some time.

I'm relatively new to python (and programming in general), so I'm struggling to figure out how to create a new tuple with the item[1] element of each tuple modified, but the item[0] element of each left untouched. All I want to do is make the second element of each tuple into a list of all those numbers. I tried to just .split() it, but tuples are immutable. How would you approach this problem, then?

Ultimately its for a beginning practice example. We're making a very primitive movie recommender based on the ratings for each film, and each of those numbers is a rating that person gave corresponding to the film.

Upvotes: 3

Views: 1308

Answers (1)

Pavel Anossov
Pavel Anossov

Reputation: 62938

Since tuples are immutable, you'll have to create new ones based on old ones:

data = [('Ben', '5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5'),
        ('Moose', '5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 -3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0')]

data = [(name, ratings.split()) for name, ratings in data]

 

If you aren't familiar with list comprehensions, this is equivalent to

new_data = []
for name, ratings in data:
    new_data.append( (name, ratings.split()) )
data = new_data

Upvotes: 5

Related Questions