1

I would like to print the number that under 130 with the name.

I have the data frame like this

name = ["a","b","c","d","e","f","g","h"]
h =    [125,120,135,115,115,130,145,130]

I have tried my code as

for i in h:
    if i < 130:
        un_130 = [name[i], h[i]]
        #print(i, un_130)
        print(i)

when I have printed i the results are correct

125
120
115
115

but when I tried to print with the name from print(i, un_30) the index error is came out.

any suggestion?

Hook Im
  • 293
  • 3
  • 11

3 Answers3

8

You could you parallel iteration with zip():

for i, n in zip(h, name):
  if i < 130:
    print(i, n)

(I don't particularly like the naming of the variables, especially i, but I chose to stay consistent with the naming used in the question.)

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • May I ask why you don't like variable naming? Isn't `i` a well known and used variable name for indices? – user3053452 Apr 06 '19 at 11:34
  • @user3053452 Reason is `i` is not indices. – Austin Apr 06 '19 at 11:36
  • @user3053452 it is in other languages, as counter variable but in this case there is no counting like you'd do in the classical `for` loop – Vulpex Apr 06 '19 at 11:36
  • Ahh my bad, I was looking at the above answer where `enumerate()` is used and got a bit confused. You're absolutely right, the naming of variables is bad. – user3053452 Apr 06 '19 at 11:37
1

Alright, so its not very pythonic as @vulpex mentioned, but you can simply iterate using range method of python to simulate the behaviour of for loop like other programming languages:

for i in range(0, len(h), 1):
if h[i] < 130:
    un_130 = [name[i], h[i]]
    print(i, un_130)
    print(i)

However, other functions such as enumerate or zip as mentioned by other answers would be more preferred and efficient to use in python generally.

Harris
  • 98
  • 2
  • 11
  • it's not equivalent, the `for` loop in python acts like a `for each` loop in other languages. You can emulate an classical `for` behaviour but that's not really the python way. it's unnecessary in this example as other answers show. – Vulpex Apr 06 '19 at 11:34
  • Oh, I agree its not "pythonic way", but I was just trying to replicate the behaviour. Forgive my lack of knowledge in some unique functions of python. – Harris Apr 06 '19 at 11:43
  • 1
    maybe note a better way as an [edit] to your post that, yes you can emulate the behaviour you'd like to use but in python the prefered way to do it is "such and such". Then it would be an really good answer in my oppinion. – Vulpex Apr 06 '19 at 11:46
0

You can use enumerate

for idx,i in enumerate(h):
    if i < 130:
        print(name[idx],h[idx])

NOTE : As long as name and h has same length

Prashant Sharma
  • 807
  • 12
  • 17