Python tricks: a combination of enumerate () and zip (), checking if a string can be converted to a number, sorting the string as a number

% python --version
Python 2.7.11 :: Anaconda 2.5.0 (64-bit)

Combine ʻenumerate ()andzip ()`

for i, (a, b) in enumerate(zip(list_a, list_b)):
    # Do something

Check if the character string can be converted to a numerical value * However, it is limited to positive integers

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

Sort strings as numbers

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 keyofsorted ()`, 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

Python tricks: a combination of enumerate () and zip (), checking if a string can be converted to a number, sorting the string as a number
Have python check if the string can be converted / converted to int
[Python] A program to find the number of apples and oranges that can be harvested
I wanted to create a program in Reverse Polish Notation in Python (determining if a string can be converted to a number)
[Python] A program that calculates the number of socks to be paired
Check if the string is a number in python
[Curse of dimensionality] If the number of sensors is changed to ∞, can anomaly be detected?
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
[Python] A program that finds the maximum number of toys that can be purchased with your money
Python> Slice> A slice offset earlier than the beginning of a string is treated as 0, and one after the end is treated as -1
How to input a character string in Python and output it as it is or in the opposite direction.
If you want a singleton in python, think of the module as a singleton
[Python] How to use the enumerate function (extract the index number and element)
How to use Python zip and enumerate
[Python] Wouldn't it be the best and highest if you could grasp the characteristics of a company with nlplot?
Article that can be a human resource who understands and masters the mechanism of API (with Python code)
Divides the character string by the specified number of characters. In Ruby and Python.
How to count the number of elements in Django and output to a template
Build a python environment to learn the theory and implementation of deep learning
[Python] A program that calculates the number of updates of the highest and lowest records
[Python] I tried to get the type name as a string from the type function
A discussion of the strengths and weaknesses of Python
What happens if you graph the number of views and ratings/comments of the video of "Flag-chan!" [Python] [Graph]
How to identify the element with the smallest number of characters in a Python list?
What to do if pvcreate produces a lot of WARNING and cannot be created
A script that can perform stress tests according to the number of CPU cores
How to check in Python if one of the elements of a list is in another list
Don't take an instance of a Python exception class directly as an argument to the exception class!
[Python] If you create a file with the same name as the module to be imported, an Attribute Error will occur.
python beginners tried to predict the number of criminals
Get the variable name of the variable as a character string.
How to get the number of digits in Python
Cut a part of the string using a Python slice
Only size-1 arrays can be converted to Python scalars
Python Note: The mystery of assigning a variable to a variable
I tried to summarize the string operations of Python
How to start a simple WEB server that can execute cgi of php and python
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
How to quickly count the frequency of appearance of characters from a character string in Python?
What seems to be a template of the standard input part of the competition pro in python3
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
How to write when you want to put a number after the group number to be replaced with a regular expression in re.sub of Python
Find out the apparent width of a string in python
[python] Change the image file name to a serial number
Get the number of specific elements in a python list
Build a Python environment and transfer data to the server
I want to know the features of Python and pip
I tried to enumerate the differences between java and python
Extract the value of dict or list as a string
How to connect the contents of a list into a string
Run the output code on the local web server as "A, pretending to be B" in python
The mystery of the number that can be seen just by arranging 1s-The number of repunits and mysterious properties-
I wrote AWS Lambda, and I was a little addicted to the default value of Python arguments
[Django] What to do if the model you want to create has a large number of fields
Understand the probabilities and statistics that can be used for progress management with a python program
Find the white Christmas rate by prefecture with Python and map it to a map of Japan
In the python metaclass, pass the comparison operator as a string to the ORM method to assemble the where clause.
[Python] The role of the asterisk in front of the variable. Divide the input value and assign it to a variable
I want to clear up the question of the "__init__" method and the "self" argument of a Python class.
[Python scraping] Output the URL and title of the site containing a specific keyword to a text file
Predict the number of cushions that can be received as laughter respondents with Word2Vec + Random Forest