'How to call a list from a user input?
I am trying to plot specific lists from a selection of lists that I want to define by user input. However I don't know how to reference the list.
from matplotlib import pyplot as plt
x = []
y = []
cd = []
cl = []
xInput = input("Please choose the x-value input: ")
yInput = input("Please choose the y-value input: ")
[...]
data_array = np.asarray(data)
aeroData = data_array.astype(np.float)
for i in range(aeroData.shape[0]):
x.append(aeroData[i][0])
y.append(aeroData[i][1])
cd.append(aeroData[i][2])
cl.append(aeroData[i][3])
plot(xInput, yInput)
plt.title("{} vs. {}".format(xInput, yInput))
plt.xlabel("{}".format(xInput))
plt.ylabel("{}".format(yInput))
plt.show
Solution 1:[1]
The user input is a string.
If the user inputs a list of values:
xInput = [float(i) for i in input("Please choose the x-value input: ").split()]
If the list is already defined and the user is just referencing the variable by name, then:
xInput = globals().get(input("Please choose the x-value input: "))
Solution 2:[2]
You need to define aeroData somewhere if you haven't already somewhere else we cannot see.
Also, plot doesn't seem to be defined either. If you are trying to define it there you need:
def plot(xInput, yInput):
plt.title("{} vs. {}".format(xInput, yInput))
plt.xlabel("{}".format(xInput))
plt.ylabel("{}".format(yInput))
plt.show()
If it is part of pyplot you should need plt.plot(xInput, yInput)
Solution 3:[3]
I think a better approach is to use a for-loop to parse the input.
The code below will parse a comma separated string and trim all non digit characters, dots and dashes casting the result to float. The float number will be then appended to a 'numeric' array.
x_input_str = input("Please choose the x-value input: ")
y_input_str = input("Please choose the y-value input: ")
xInput = []
for x in x_input_str.split(","):
x = re.sub(pattern=r"([^0-9\.\-])", repl="", string=x.strip())
xInput.append(float(x))
yInput = []
for y in y_input_str.split(","):
y = re.sub(pattern=r"([^\d.-])", repl="", string=y.strip())
yInput.append(float(y))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eme Eme |
| Solution 2 | Hamish Wormald |
| Solution 3 | pinxau1000 |
