简体   繁体   中英

how can I print both positive and negative indexes together with its corresponding element?

In the following code I want to print in the way mentioned in the question what am I getting is this:

https://prnt.sc/oEjjTyr_dtdu

Tried this hoping they would come together with their corresponding element on the same line with like this

(index)  (element)
-1  2        3
-2  1        2
-3  0        1

can you show me alternate solution also?

t=[]
n=int(input("enter how many elements"))
for i in range(0,n):
    a=int(input("enter element"))
    t.append(a)
t=tuple(t)
print(t)
a=reversed(t)
for i,e in *enumerate(a,-n),*enumerate(t,0):
    print((i),(e))
t=[]
n=int(input("enter how many elements: "))
for i in range(0,n):
    a=int(input("enter element: "))
    t.append(a)
for num in t[::-1]: # Here t is a list, you can use tuple in the likewise manner. 
  print(t.index(num)-len(t),t.index(num),num)

Result:

enter how many elements:3
enter element:1
enter element:2
enter element:3
-1 2 3
-2 1 2
-3 0 1

This is in the order you asked.

To get the corresponding negative index, you should subtract the length of the tuple from positive index.

t = []
n = int(input("enter how many elements"))
for i in range(0, n):
    a = int(input("enter element"))
    t.append(a)
t = tuple(t)

for i in range(len(t)):
    print(f"{i-len(t)} {i}\t{t[i]}")

output:

enter how many elements: 3
enter element: 1
enter element: 2
enter element: 3
-3 0    1
-2 1    2
-1 2    3

If you want to print them in reverse order (like what you showed in the question, just add reversed() to the range:

t = []
n = int(input("enter how many elements: "))
for i in range(0, n):
    a = int(input("enter element: "))
    t.append(a)
t = tuple(t)

for i in reversed(range(len(t))):
    print(f"{i-len(t)} {i}\t{t[i]}")

output:

enter how many elements: 3
enter element: 1
enter element: 2
enter element: 3
-1 2    3
-2 1    2
-3 0    1

Just for fun, alternatively you can try this one: It is using the negate index - ~0 becomes -1, ~1 becomes -2 etc.

# first, input part is done already. 

for i in range(len(t)):
    print(f" {~i} {len(t) -i-1} \t {t[~i]} ")  # minus 1, because list is 0-based

    
 -1 2    3 
 -2 1    2 
 -3 0    1 

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