3

I have a file with name ids.txt also file with name names.txt

in the ids.txt file we see:

23
422
5123
642
8743

the content of the names.txt file:

jon1
jon2
jon3
jon4
jon5

I want to sort it like this:

23 jon1
422 jon2
5123 jon3
642 jon4
8743 jon5;

and when it's sorted the last one set it like this

8743 jon5;

what I'm doing is :

IDs = file("IDs.txt").read().splitlines()
names = file("names-specialitys.txt").read().splitlines()
for i in IDs:
    for n in names:
        print i, n

but it's print it like this:

23 jon1
422 jon1
5123 jon1
642 jon1
8743 jon1
23 jon2

... etc

Ben Aubin
  • 5,542
  • 2
  • 34
  • 54
emzemzx
  • 165
  • 3
  • 11
  • 1
    `zip` the two lists. – Karoly Horvath Nov 12 '15 at 23:02
  • In your question you say 'sort', but the list [22, 422, 5123, 642, ...] is not sorted (in ascending or descending order anyway!). I think you mean that you want to pair the items in the two lists together. – Alasdair Nov 12 '15 at 23:15

2 Answers2

4

You can zip the lists together.

for i, n in zip(IDs, names):
    print i, n

To display the last row differently, you could slice the lists before you zip them. Then print the last row separately.

for i, n in list(zip(IDs[:-1], names[:-1]):
    print("{} {}".format(i, n))
print("{} {};".format(IDs[-1], names[-1]))
Alasdair
  • 298,606
  • 55
  • 578
  • 516
1

"Zip"y explanation:

Python has a great zip() function built in. It takes 2 lists, and joins each item with the item at the same point in an array.

Example:

a = b = c = range(20)
zip(a, b, c) #=> [(0, 0, 0), (1, 1, 1), ... (18, 18, 18), (19, 19, 19)]

Your Solution:

for i, n in zip(IDs, names):
    print i + " " + n
Ben Aubin
  • 5,542
  • 2
  • 34
  • 54