-1

[Problem:] I am having trouble sorting a column that includes both letters and digits.

[Input] My column looks like this: Reference

Test1
Test2
Test11

[Code]

import csv
import operator
sample = open (r'test.csv','r')
csv1 = csv.reader(sample, delimiter = ',')
sort = sorted (csv1,key=operator.itemgetter(154))

[Current output]

Test1
Test11
Test2

[Desired output]

Test1
Test2
Test11

Therefore can u please share a hint on this.

Take care

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
serte
  • 1
  • 3

1 Answers1

0

You can use re to find the digits and cast to int :

import re

sort = sorted(csv1,key=lambda x: int(re.search("\d+",x[154]).group()))

If you have some strings without digits:

import re

sort = sorted(csv1,key=lambda x: x[154] if x.isalpha() else int(re.search("\d+",x[154]).group()))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • OP was using `operator.itemgetter(154)` as the key so minor adjustment needed: `lambda x: int(re.search("\d+",x[154]).group())` – Sam Jul 12 '15 at 09:24
  • Hi guys, thanks for quick reply. I've tried your approach and I got: AttributeError: 'NoneType' object has no attribute 'group'. Current code is: import csv import operator sample = open (r'test.csv','r') csv1 = csv.reader(sample, delimiter = ',') sort = sorted(csv1,key=lambda x: int(re.search("\d+",x[154]).group())) – serte Jul 12 '15 at 10:24
  • @ HappyLeapSecond; yes the code: "import re; sorted(lst, key=lambda x: int(re.findall(r'\d+$', x)[0]))" (from duplicate question) works for list, but it seems I cannot get it to work on my column. I will try to figure out what I am missing – serte Jul 12 '15 at 10:33
  • @serte. Then there are values that have no digits in the string – Padraic Cunningham Jul 12 '15 at 10:36
  • Yes. The "Reference" column header has no digits. I will try: to skip header or append "0" to column header. – serte Jul 12 '15 at 10:52
  • Thanks for support. problem solved – serte Jul 12 '15 at 11:21
  • Yesm just header = next(csv1) will skip the header – Padraic Cunningham Jul 12 '15 at 11:42