Code Generate Outputs For All Items In The List In Python Script
Solution 1:
Several problems:
In your first bit of code, you have a listfruit
, which contains the list of fruit passed via a command-line argument. If it isn't specified, you have a default of "apple, pineapple, banana, orange"
.
Keep in mind: fruit
is a list.
Now, here:
ifsys.argv[3]==fruit:
You're comparing one of the raw arguments (a string) with a list. First of all, why are you accessing sys.argv directly if you're using argparse? Second, why are you comparing a string to a list?
Also, this line:
forfruitin fruits
This "fruit" is shadowing (if different scope) or overwriting the old fruit
variable. In this case you presume that the user hasn't supplied this parameter so doing so doesn't matter, but keep in mind that that's confusing—you should really be using more descriptive variables!
fruit =[str(item) for item in args.fruit.split(',')]
Note that the default is "apple, pineapple, banana, orange"
- it has spaces. So here fruit = ["apple", " pineapple", " banana", " orange"]
- those spaces are in there and will break string comparisons (if you were going to do any string comparisons). Suggest fixing this line to:
fruit = [str(item).strip() for item in args.fruit.split(',')]
strip()
on a string will get rid of leading and trailing whitespace.
For the last bit of code, I suggest:
fruits_names = [str(item) foritemin fruits]
forarg_fruitin fruit: # foreach fruit passed as an argument
if arg_fruit in fruits_names: # check if it's a valid fruit first
forsizein sizes: # if it's valid, "compile"forall sizes
compile()
Note that I took out the if statement entirely, because you have a default value for args.fruit
that lists all the fruit, so there's no situation in which you'd not have an args.fruit
value to iterate over. If you wanted to rely on "no fruits argument = use the full list", set the fruit argument's default to None
and check for if args.fruit is None
instead.
Also, your variables are poorly named and make the above code confusing (someone reading the above might ask: "wait, what's the difference between the fruit
and fruits
variable?"). Let me suggest renames:
- fruits → valid_fruits
- sizes → valid_sizes
- fruit → arg_fruit_list
That way, it's clear that some of those lists are the valid values, and the other list is the one passed via command line.
Solution 2:
Variable 'fruit' is a list, but you compare it with a string:
fruit =[str(item) for item in args.fruit.split(',')]
if sys.argv[3] == fruit: # this will always be False
Post a Comment for "Code Generate Outputs For All Items In The List In Python Script"