简体   繁体   中英

How to produce a list of odd indices from a number in Python?

I want to produce a list containing only the odd indices of a Python integer number.

here is what I tried to do:

number = 5167460267890853
numberList = [num for num in str(number)]
oddIndex = [num for num in numberList if numberList.index(num) % 2 == 0]
print(oddIndex)

Output:

['5', '6', '4', '6', '0', '6', '8', '0', '8', '5']

Expected output:

['5', '6', '4', '0', '6', '8', '0', '5'] 

You can use string slicing with a step of 2 . Convert the number to a string, take only the odd indices and than convert to a list.

Using the this approach on your attempt, you could try:

number = 5167460267890853
numberList = [num for num in str(number)]
numberList = numberList[::2]

or just use the list built-in function:

number = 5167460267890853
oddIndex = list(str(number)[::2])

Both yield the desired output.

Answers to a similar question also use similar technique here

list.index() will return the index of the first seen element in the list. You can use enumerate() instead like this example:

number = 5167460267890853
out = [num for k, num in enumerate(str(number)) if not (k % 2)]
print(out)
# ['5', '6', '4', '0', '6', '8', '0', '5']

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