I have this python list array:
yards = [['85', '110', '90', '130', '115', '105', '95', '87', '85'], ['-', '90', '-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-', '-', '-']]
but I want to replace all '-' with a zero (0).
yards = [[85, 110, 90, 130, 115, 105, 95, 87, 85], [0, 90, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]
This code below is not working as it should because it's not looping all elements only the one defined as yards[1]. How do make it so that any size of 2D list array with element ('-') gets changed to a zero?
print(len(yards))
numeric_types = [str]
yards = [x for x in yards[1] if type(x) in numeric_types]
print(yards)
for i in range(len(yards)):
if yards[i] == '-':
yards[i] = 0
print(yards) # output of the changed list
4
['-', '90', '-', '-', '-', '-', '-', '-', '-']
[0, '90', 0, 0, 0, 0, 0, 0, 0]
Convert to numpy:
import numpy as np
yards = [['85', '110', '90', '130', '115', '105', '95', '87', '85'], ['-', '90', '-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-', '-', '-']]
arr = np.array(yards)
Then to set all the occurrences of '-' to 0, do the following:
arr[arr == '-'] = 0
for l in range(len(yards)):
for i in range(len(l)):
if l[i] == '-':
yards[l][i] = 0
This loops through each sub list and finds the '-' and changes it's value to 0.
if you're already using numpy for something, this is a very easy one-liner:
x = np.array(yards)
np.where(x=='-',0,x).tolist()
output:
[['85', '110', '90', '130', '115', '105', '95', '87', '85'], ['0', '90', '0', '0', '0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0', '0', '0', '0', '0'], ['0', '0', '0', '0', '0', '0', '0', '0', '0']]
you could also use numpy to typecast the array to ints, floats, etc. if you wanted once the -'s are replaced with numbers
Hendy's answer would output this error:
TypeError: object of type 'int' has no len()
here's how to fix this:
for l in range(len(yards)):
for i in range(len(yards[l])):
if yards[l][i] == '-':
yards[l][i] = 0
You can use nested list comprehensions to convert '-' to 0 (and convert other elements to integers):
[ [0 if r == '-' else int(r) for r in row]
for row in yards
]
[[85, 110, 90, 130, 115, 105, 95, 87, 85],
[0, 90, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0]]
You can iterate through the the 2d list:
for x in range(len(yards)):
for y in range(len(yards[x])):
if yards[x][y] == '-':
yards[x][y] = 0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.