[英]Python accessing tuple index by value
Let's say I have a tuple that is (4, 5, 6, 7, 8). 假设我有一个(4,5,6,7,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? 输出示例:5、6、7、8、6、7、8、7、8、8。有什么帮助吗? 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: 如果要将它们全部加入到输出元组中,则以下1-liner效率不高:
>>> 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
: 一种更有效的方法是使用
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] 输出为[5,6,7,8,6,7,8,7,8,8]
According to the Python documentation, tuples are immutable objects . 根据Python文档, 元组是不可变的对象 。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.