Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

iterating indexes of items in a list with a condition python

i would want to print out the indexes of the items that are 'H' but it is stuck in one item.

here's my code:

import random

def coinflipping():
    #generating 100 coin flips
    coins = []
    coin_sides = ['H', 'T']
    for i in range(100):
        coins.append(coin_sides[random.randint(0, 1)])
    return coins

sides = coinflipping()
print(sides)

for i in sides:
    if i == 'H':
        print(sides.index(i))

and here's the output:

output


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is one way of doing it:

import random

def coinflipping():
    #generating 100 coin flips
    coins = []
    coin_sides = ['H', 'T']
    for i in range(100):
        coins.append(coin_sides[random.randint(0, 1)])
    return coins

sides = coinflipping()
print(sides)

for i,t in enumerate(sides):
    if t == 'H':
        print(i)

enter image description here

Remember that index returns the first occurrence of an item. And since sides are your static list it always returns 1 because H is first met in the index 1 in your random case.

You can check enumerate here.

Another way of doing it is this:

a = [np.random.choice(['H','T']) for x in range(100)]
result = [x[0] for x in enumerate(a) if x[1]=='H']

# returns a list of indexes where 'H' was flipped.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...