Home > Net >  Copying specific values from one list to another, type conversion
Copying specific values from one list to another, type conversion

Time:11-23

I have a list x with values:

[0.09086322  -0.66400483  -0.85750224, ... 73.92927078, 5.18024081, -17.12200886]

Here, I want to copy values in the range (-50, 50) from list x to another list y.

I have tried implementing the following code, but it doesn't seem to work

y = []
for i in x:
    if x[i] >= -50 and x[i] <=50:
    y.append(x[i])

I get the following error:

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and
integer or boolean arrays are valid indices

CodePudding user response:

Use i instead of x[i] if you want to iterate on the list indexes, use for i in range(x):

CodePudding user response:

You are directly using the float values from your x list as indices, but x[0.09086322] is an invalid list access. You should directly use the values.

You can use a list comprehension rather than a for loop, it is easier to understand in my opinion :

>>> x = [-50.1, -50.2, 0.1, 0.2, 0.3, 50.1, 50.2]
>>> y = [v for v in x if v >= -50 and v <= 50]
>>> y
[0.1, 0.2, 0.3]

CodePudding user response:

There is no need to write x[i] as you have defined x (the structure you want to loop through) in the for loop already. Try:

y = []
for i in x:
    if i >= -50 and i <=50:
        y.append(i)

CodePudding user response:

When you run for i in x:, i is each element in the list rather than the index. You can check this by running the below:

for i in x:
    print(i)

Output:

0.09086322
-0.66400483
-0.85750224
73.92927078
5.18024081
-17.12200886

So when calling x[i] you are trying to call x[0.09086322], which isn't possible. There are 2 ways to fix this code, the first is to replace x[i] with just i:

y = []
for i in x:
    if i >= -50 and i <=50:
        y.append(i)

Or loop through the indexes of x like below:

y = []
for i in range(len(x)):
    if x[i] >= -50 and x[i] <=50:
    y.append(x[i])

CodePudding user response:

x = [0.09086322,-0.66400483,-0.85750224,73.92927078,55.18024081,-17.12200886]
y = []
for i in range(len(x)):
    if x[i]>= -50.0 and x[i] <=50.0:
        y.append(x[i])
print(y)
  • Related