简体   繁体   中英

Python accessing tuple index by value

Let's say I have a tuple that is (4, 5, 6, 7, 8). I want to iterate through it, then each iteration only print the numbers after that index. So like this:

for i in tuple:
    #print values to the right of i

Example output: 5, 6, 7, 8, 6, 7, 8, 7, 8, 8. Any help? I know how to access a tuple value by its index but not by the reverse.

Do you mean something like this?

t = (4, 5, 6, 7, 8)
for i, _ in enumerate(t, 1):
  print(t[i:])

# (5, 6, 7, 8)
# (6, 7, 8)
# (7, 8)
# (8,)
# ()

If you want to join them all into an output tuple, the following 1-liner will do it inefficiently:

>>> sum((t[i:] for i, _ in enumerate(t, 1)), ())
(5, 6, 7, 8, 6, 7, 8, 7, 8, 8)

A more efficient way would be to use itertools.chain.from_iterable :

tuple(itertools.chain.from_iterable(
    t[i:] for i, _ in enumerate(t, 1)))

Try

tuple = (4,5,6,7,8)
z = []
for i in range(len(tuple)):
    for j in tuple[i+1:]:
        z.append(j)

output is [5,6,7,8,6,7,8,7,8,8]

According to the Python documentation, tuples are immutable objects . So if you want to change the output that you produce each time you iterate through the tuple, you will need to set a new variable in your loop each time. Something like this:

t = (5,6,7,8)
for i,n in enumerate(t):
    tnew = t[i:]
    print tnew

Using a list comprehension:

t = (4, 5, 6, 7, 8)
>>> [i for n in range(len(t)) for i in t[n+1:]]
[5, 6, 7, 8, 6, 7, 8, 7, 8, 8]

Or if you want a tuple, you can use a generator expression ( tuple comprehension ?):

>>> tuple(i for n in range(len(t)) for i in t[n+1:])
(5, 6, 7, 8, 6, 7, 8, 7, 8, 8)

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