cbkhia
cbkhia

Reputation: 55

How do I sort by the first element of each line?

I am attempting to sort the first element of each line alphabetically but struggling to get this to work.

[['^', 'G', 'A', 'T', 'T', 'A', 'C', 'A', '!']]
[['G', 'A', 'T', 'T', 'A', 'C', 'A', '!', '^']]
[['A', 'T', 'T', 'A', 'C', 'A', '!', '^', 'G']]
[['T', 'T', 'A', 'C', 'A', '!', '^', 'G', 'A']]
[['T', 'A', 'C', 'A', '!', '^', 'G', 'A', 'T']]
[['A', 'C', 'A', '!', '^', 'G', 'A', 'T', 'T']]
[['C', 'A', '!', '^', 'G', 'A', 'T', 'T', 'A']]
[['A', '!', '^', 'G', 'A', 'T', 'T', 'A', 'C']]
[['!', '^', 'G', 'A', 'T', 'T', 'A', 'C', 'A']]

Tried the sort and sorted function aswell as pandas but can't seem to make it work

with open ('BWT_test.txt','r') as seq1:
    sequence1 = seq1.read()
    seq1.read()
list1 = list(sequence1)
list1.insert(0,'^')
list1.append('!')
for seq1 in range(len(list1)):
    table1 = [list1[seq1:] + list1[:seq1]]
    sorted(table1)
    print(table1)

The code should organsie the list to this:

[['A', 'C', 'A', '!', '^', 'G', 'A', 'T', 'T']]
[['A', 'T', 'T', 'A', 'C', 'A', '!', '^', 'G']]
[['A', '!', '^', 'G', 'A', 'T', 'T', 'A', 'C']]
[['C', 'A', '!', '^', 'G', 'A', 'T', 'T', 'A']]
[['G', 'A', 'T', 'T', 'A', 'C', 'A', '!', '^']]
[['T', 'A', 'C', 'A', '!', '^', 'G', 'A', 'T']]
[['T', 'T', 'A', 'C', 'A', '!', '^', 'G', 'A']]
[['^', 'G', 'A', 'T', 'T', 'A', 'C', 'A', '!']]
[['!', '^', 'G', 'A', 'T', 'T', 'A', 'C', 'A']]

Upvotes: 0

Views: 154

Answers (1)

N Chauhan
N Chauhan

Reputation: 3515

sorted(data, key=lambda x: x[0])

Or...

from operator import itemgetter
sort = sorted(data, key=itemgetter(0))

Change the loop to this:

rotations = []
for seq1 in range(len(list1)):
    table1 = list1[seq1:] + list1[:seq1]
    rotations.append(table1)
rotations = sorted(rotations, key=lambda x: (x[0] not in string.ascii_letters, x[0]))
print([x[-1] for x in rotations])

Upvotes: 3

Related Questions