Python: I want to put a serial number in front of the print with the list for door

Asked 2 years ago, Updated 2 years ago, 12 views

A = set(["a","b","c"])

B = set(["a","b","c","d","e","f"])

list1 = A & B

for x in list1 :

   print(x)

Write with this code.

a
b
c

That's how it's written like this I want to put 1, 2, 3 on the front.

python

2022-09-20 16:26

2 Answers

If you want to put 1. on the printout, you can use the code below.

A = set(["a","b","c"])
B = set(["a","b","c","d","e","f"])
list1 = A & B
count = 0
for x in list1:
    count += 1
    print(str(count) + "." + str(x))


2022-09-20 16:26

The psychedelic answer to these problems is enumerate.

for i, x in enumerate(list1):
  print(i, x)

I want to start with 1.

for i, x in enumerate(list1, start=1):
  print(i, x)

If you want to include .,

for i, x in enumerate(list1, start=1):
  print(f"{i}. {x}")


2022-09-20 16:26

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.