Splitting a sequence of number into a list (Python) - string

I wanted to ask you how can I split in Python for example this string '20020050055' into a list of integer that looks like [200, 200, 500, 5, 5].
I was thinking about enumerate but do you have any example of a better solution to accomplish this example? thanks

One approach, using a regex find all:
inp = '20020050055'
matches = re.findall(r'[1-9]0*', inp)
print(matches) # ['200', '200', '500', '5', '5']
If, for some reason, you can't use regular expressions, here is an iterative approach:
inp = '20020050055'
matches = []
num = ''
for i in inp:
if i != '0':
if num != '':
matches.append(num)
num = i
else:
num = num + i
matches.append(num)
print(matches) # ['200', '200', '500', '5', '5']
The idea here is to build out each match one digit at a time. When we encounter a non zero digit, we start a new match. For zeroes, we keep concatenating them until reaching the end of the input or the next non zero digit.

Related

match a pattern in text and read it to different variables

I have the following pattern: <num1>-<num2> <char a-z>: <string>. For example, 1-3 z: zztop
I'd like to parse them to n1=1, n2=3, c='z', s='zztop'
Of course I can do this easily with splitting but is there a more compact way to do that in Python?
Using re.finditer with a regex having named capture groups:
inp = "1-3 z: zztop"
r = re.compile('(?P<n1>[0-9]+)-(?P<n2>[0-9]+) (?P<c>\w+):\s*(?P<s>\w+)')
output = [m.groupdict() for m in r.finditer(inp)]
print(output) # [{'n1': '1', 'n2': '3', 'c': 'z', 's': 'zztop'}]

What does int(n) for n mean?

In order to put the input into a list:
numbersList = [int(n) for n in input('Enter numbers: ').split()]
Can someone explain what does 'int(n) for n in' mean?
How do I improve this question?
The entire expression is referred to as a List Comprehension. It's a simpler, Pythonic approach to construct a for loop that iterates through a list.
https://www.pythonforbeginners.com/basics/list-comprehensions-in-python
Given your code:
numbersList = [int(n) for n in input('Enter numbers: ').split()]
Lets say you run the code provided, you get a prompt for input:
Enter numbers: 10 8 25 33
Now what happens is, Python's input() function returns a string, as documented here:
https://docs.python.org/3/library/functions.html#input
So the code has now essentially become this:
numbersList = [int(n) for n in "10 8 25 33".split()]
Now the split() function returns an array of elements from a string delimited by a given character, as strings.
https://www.pythonforbeginners.com/dictionary/python-split
So now your code becomes:
numbersList = [int(n) for n in ["10", "8", "25", "33"]]
This code is now the equivalent of:
numbersAsStringsList = ["10", "8", "25", "33"]
numberList = []
for n in numbersAsStringsList:
numberList.append(int(n))
The int(n) method converts the argument n from a string to an int and returns the int.
https://docs.python.org/3/library/functions.html#int
For example input('Enter numbers: ').split() returns an array of strings like ['1', '4', '5']
int(n) for n in will loop throug the array and turn each n into an integer while n will be the respective item of the array.
let us try to understand this list comprehension expression though a simple piece of code which means the same thing.
nums = input('Enter numbers: ') # suppose 5 1 3 6
nums = nums.split() # it turns it to ['5', '1', '3', '6']
numbersList = [] # this is list in which the expression is written
for n in nums: # this will iterate in the nums.
number = int(n) # number will be converted from '5' to 5
numbersList.append(number) # add it to the list
print(numbersList) # [5, 1, 3, 6]

Python 3.6 - How to search through a 2D list and return true or false if an item matches user input

I am using EDX to start learning python and I am stuck in a project that requires me to create a tic tac toe game.
I believe I have managed to complete most of the functions but when I tried to run the function that checks whether a position is available to be marked as X or O, I always get a false reading. It returns true only for the 7 and not for the rest of the items.
board = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3']]
location = input(" Turn, select a number (1, 9): ")
def available(location, board):
for row in board:
for col in row:
if col==location:
return True
else:
return False
print(available(location,board))
I decided to separate the function from the rest of the code. The code above should be able to search the 2D list and if it finds the number that the user has entered to return true or false. When it does that another function is executed to change that number to X or O depending the player. I tried to run the function without the function and with print instead of return and works fine.
board = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3']]
location = input(" Turn, select a number (1, 9): ")
for row in board:
for col in row:
if col==location:
print("True")
else:
print("False")
Any idea what I am doing wrong?
Let's look at your if else statement.
When the input number is not 7, we do not return true, instead we go to the else and immediately return false without checking the rest of the numbers.
The solution is to remove the else, and just return false only after iterating through every cell.
When you change the returns to prints this bug disappears because you are no longer returning, and therefore execution doesn't stop early.
def available(location, board):
for row in board:
for col in row:
if col==location:
return True
return False
The key insight here is that returning from a function, exits the function.
To overcome the problem you identified, you could for instance flatten your list by using a list comprehension and check for the existence of location in it:
board = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3']]
location = input(" Turn, select a number (1, 9): ")
def available(location, board):
#collect all elements from all sublists in a list
allfields = [i for j in board for i in j]
#location element of this list?
if location in allfields:
return True
return False
print(available(location,board))
You can use any for a more Pythonic version.
def available(location, board):
return any(any(i == location for i in row) for row in board)

How do I join portions of a list in Python

Trying to join only portions of a large list that has numbers in it. For example:
h = ['9 This is the way this is the way 10 to program a string 11 to program a string']
##I've tried...
h[0].split()
z = []
h = ['9', 'This', 'is', 'the', 'way', 'this', 'is', 'the', 'way', '10', 'to', 'program', 'a', 'string', '11', 'to', 'program', 'a', 'string']
for i in h:
while i != '10':
z.append(i)
But the program runs an infinite loop. I've also tried if statements, if i != '10' then z.append(i). Basically, I have large portions of scripture that is in a list as a single string and I'd like to quickly extract the verses and put them in their own separate list. Thank you
Edit: I've tried...
h= ['9 nfnf dhhd snsn nana na 10 hfhf gkg utu 11 oeoe ldd sss', 'kgk hfh']
y = h[0].split()
print (y)
z = []
for i in y:
if i != "10":
z.append(i)
break
print (z)
Output is the split list and 'z' prints '9' only. I've also changed the break to the correct indentation for the 'for' loop
First of all, use the result you get from h[0].split(). You can do this by using h = h[0].split()
Now, lets get to the loop. It's going into an infinite loop because the for loop is picking the first i which is "9" and then while i != "10", it keeps appending i to z. i will never equal "10". Thus, the infinite loop. I think what you want here is:
for i in h:
if i != "10":
z.append(i)
else:
break
This will append every value of h into z until i is equal to "10". Let me know if you need more help and I'll be happy to edit!
Try this for extracting all numbers in z:
h = ['9 This is the way this is the way 10 to program a string 11 to program a string']
##I've tried...
h = h[0].split()
z = []
for i in h:
try:
z.append(eval(i))
except:
pass
print z
output:
[9, 10, 11]
[Finished in 0.0s]

how do i remove comma in the list using for loop?

I have this code:
a = []
num = input('Enter numbers *Separate by using commas:')
for i in num:
a.append(i)
print(a)
and I get this:
Enter numbers *Separate by using commas:1,2,3
['1', ',', '2', ',', '3']
how do I remove the comma?..and I need to use the for loop...thanks
You can use this (by default prevents "," to enter in your array in the first place and functional for multi-digit numbers as you pointed out)-
a = []
num = input('Enter numbers *Separate by using commas:')
num = num.split(",") #splits the input string with "," delimiter
for i in num:
a.append(i)
print(a)

Resources