% python --version
Python 2.7.11 :: Anaconda 2.5.0 (64-bit)
and
zip ()`for i, (a, b) in enumerate(zip(list_a, list_b)):
# Do something
Use the string method ʻisdigit () `. Returns true if there are only numbers in the string, false otherwise.
a = '100'
b = 'hoge100'
a.isdigit() # => True
b.isdigit() # => False
You can also check various things with ʻis * () `.
reference:
-5. Embedded — Python 2.7.13 documentation -Check if a character string can be converted to a number with Python | A memo for forgetting the brain immediately
Thing you want to do:
a = ['2', '1', '3', '33', '22', '11']
sorted(a) # => ['1', '11', '2', '22', '3', '33']
# I need `['1', '2', '3', '11', '22', '33']
Pass ʻint () to the keyword argument
keyof
sorted ()`, convert each element (string) to a number and sort.
sorted(a, key=int) # => ['1', '2', '3', '11', '22', '33']
An error will occur if the list to be sorted contains a character string that cannot be converted to a numerical value. In that case, do as follows.
a = ['2', '1', '3', '33', '22', '11', 'hoge', 'fuga']
sorted(a, key=lambda x: int(x) if x.isdigit() else x) # => ['1', '2', '3', '11', '22', '33', 'fuga', 'hoge']
Reference: 2. Built-in functions — Python 2.7.13 documentation
Recommended Posts