[Tutor] Updating index of a list

Steven D'Aprano steve at pearwood.info
Fri Oct 9 00:37:00 CEST 2015


Hi Andrea, and welcome.

My responses inline, below.


On Thu, Oct 08, 2015 at 03:40:38PM -0400, Andrea Nguy wrote:

> Hi there,
> 
> I’m trying to learn some Python programming on my own. What’s 
> happening is that I am trying to take a list of a list as such: [['1', 
> ' james', ' 1', ' 90'], ['2', ' alice', ' 1', ' 95'], ['5', ' jorgen', 
> ' 1', ' 99’]] (it continues) from a text file.

Okay, I assume you know how to read the data from the text file and 
build the list of lists. If not, let us know. I'll also assume that the 
leading spaces in some of the items are deliberate.

What version of Python are you using? That may make a difference to the 
answers.

So let's just say we have:

thelist = [['1', ' james', ' 1', ' 90'], 
           ['2', ' alice', ' 1', ' 95'], 
           ['5', ' jorgen', ' 1', ' 99’],
           ]


> However, what I am trying to do take the indexes of thelist[0][1] and 
> theist[0][3] and times them by a float number - returning the list 
> with all of the values multiplied according to the float.

I'm not really sure I understand what you are trying to do here. If I 
take you literally, you want something like this:

- take thelist[0][1]  # returns ' james'
- extract the indexes of that string  # returns [0, 1, 2, 3, 4, 5]
- take thelist[0][3]  # returns ' 90'
- extract the indexes of that string  # returns [0, 1, 2]
- concatenate with the first list  # returns [0, 1, 2, 3, 4, 5, 0, 1, 2]
- multiply by some mystery float (say, 1.5)  
  # returns [0.0, 1.5, 3.0, 4.5, 6.0, 7.5, 0.0, 1.5, 3.0]


This is certainly possible, but I'm not sure that it is what you want. 
Can you confirm that it is, or explain a little better what you want? 
If possible, show your expected output.

But, for the record, here is one way to do the above:

results = []
for i in (1, 3):
    word = thelist[0][i]
    results.extend(range(len(word)))

for i, n in enumerate(results):
    results[i] = n*1.5

print(results)


You may or may not understand all that code. If you don't, please say so 
and we'll explain.


> Is this possible? I am trying to iterate that throughout the entire 
> list or would it be easier if I tried to change the list of the list 
> into a dictionary for efficiency?

If you converted the list-of-lists into a dictionary, what would it look 
like?


P.S. please keep your replies on the list, so that others may help, or 
learn from your questions.



-- 
Steve


More information about the Tutor mailing list