简体   繁体   中英

Adding 1 to elements of an empty list using another list to count up (maybe with += ?)

I'm very new to python and programming, so please keep answers simple if you can.

I'm trying to create a script that will add 1 to elements in an empty list based on an unordered other list. My inputs are shown below as well as my desired output. Since 5 appears twice in the 'data' list, element 5 in 'input' should count up to 2.

Here's the code I tried, with the error it gives:

input = [0, 0, 0, 0, 0]
data = [5, 1, 2, 5]

input[data] += 1

#desired output: [1, 1, 0, 0, 2]

The error this gives:

TypeError: list indices must be integers, not list

I'm confused, because I have a list of integers, but I guess that doesn't count as type 'int'. I searched to try to convert a list to integers, but all the solutions I found result in still having type 'list'. I'm thinking += might not be the right operator to use in this instance, but I'm not sure what else to use.

Edit: Oops, I forgot about lists starting at 0. Thanks for pointing that out, and thanks for all the great answers! Hard to choose just one.

You will have to loop through the data list, since you cannot pass a list to the index of a list (which is what the error is telling you).

Something like:

for ind in data:
    input[ind]+=1

Note also that Python lists are 0-indexed, which means the first element is called using:

input[0]

I notice you have 5's in your data list - there is no 5th element in your input - the indices are 0,1,2,3,4 so you'd need to modify your code (or input list) for it to run without an error.

Python basically is telling you, you can't use a list as an index to another list . When you try to index the input list with the data list, Python raises an error because the index object is not valid(Also, while I'm at it, input is a reserved keyword in Python and should not be used as variable name . But for sake of clarity, I'll keep using it).

This code

input[data] += 1

is equivalent to this

input[[5, 1, 2, 5]] += 1

Which of course makes no sense, and Python complains.

Now if I understand you right, you want to increment the element in input which corresponds to the element in data , each time an occurrences of the element is found. If this is the case, a dictionary would be a much better choice.

Each key in the dictionary would the a number from data , and the value of each key is zero. Each time an occurrence of a key is found, the corresponding value will be incremented. eg.

input = {5: 0, 2:0, 1:0}
data = [5, 1, 2, 5]

for element in data:
    inpt[element] += 1

However, a much better idea would be to use the collections.Counter() class:

from collections import Counter

data = [5, 1, 2, 5]
input = Counter(data)

What you can do to speed things up is to use a collections.Counter to count the number of times it appeared in data.

input = [0, 0, 0, 0, 0]
data = [5, 1, 2, 5]


from collections import Counter
counted = Counter(data)
for i, b in counted.items():
    input[i-1] = b

And as a side note, input or any other pre-defined names isn't good variable names since they could mess things up in the future.

A easier way to create the input is to do this in case you don't know how many zeroes you need.

input = [0 for _ in range(max(a))] # place this after you defined counted

And I believe you don't even need to do this, just use the Counter instance can surely get the job done. Counter({5: 2, 1: 1, 2: 1}) It behaves almost the same way as a dict.

list is accessed by its index suppose list1 = [3,4,1,2,5] to access list element i need to provide index of that element. index start with 0 to n. suppose i want to access second element of list

print list1[1]

#out: 4

to iterate through list element

for i in list1:
   print list1[i]

in your code you are accessing list index by another list.

welcome to python!

Your problems arise from a misunderstanding of how indexing works. There are two problems. The first has to do with data types, and is neatly encapsulated in your error message: TypeError: list indices must be integers, not list . Let's break this down a bit:

'Indexing' is what happens when you use square brackets after a list to access a particular element of that list. ie if a is a list, a[N] will return the Nth element of a, where N is an integer. You can only access one element at a time when indexing. Python doesn't know what to do if you give it a list, and your error message is basically telling you "You've asked me to index a list with another list, and I don't know how to do that. I only understand integers!".

Because you can only index one value at time, the best way of doing what you're trying to do is with a loop:

for i in data:
    input[i] += 1

How is this different from what you've done? Using a loop goes through each element of data individually, temporarily calls it i , and uses that to index input, and then the += 1 does what you were originally trying to do.

HOWEVER , if you run the loop, you'll get a second error message, because of a different problem. This error will say IndexError: list index out of range , which tells you that you're requesting to access a part of the list that doesn't exist. But why? input has 5 items in it, and you're only asking it for indices between 1 and 5! This error arises because Python's indexing starts at zero, not one. Valid indices of the input list are therefore [0, 1, 2, 3, 4] , not [1, 2, 3, 4, 5] . Because your data list contains the number 5, at some point during the loop i = 5 , and you're asking to access the sixth element of index ( index[5] ), which does not exist.

You can get past this either by changing your data list so that it contains valid indices, or adjusting your loop so that:

for i in data:
    input[i - 1] += 1

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM