Home > Net >  Do I need to convert str to list?
Do I need to convert str to list?

Time:09-24

rainfall_mi is a string that contains the average number of inches of rainfall in Michigan for every month (in inches) with every month separated by a comma. Write code to compute the number of months that have more than 3 inches of rainfall. Store the result in the variable num_rainy_months. In other words, count the number of items with values > 3.0. Hard-coded answers will receive no credit.

Do I need to convert str "rainfall_mi" to list? I know, both ways work.

I know that code executes by both ways. But which's way is better?

rainfall_mi = "1.65, 1.46, 2.05, 3.03, 3.35, 3.46, 2.83, 3.23, 3.5, 2.52, 2.8, 1.85"
num_rainy_months = 0
rainfall_no = list(rainfall_mi.split(","))
# or
# rainfall_no = rainfall_mi.split(",")
for data in rainfall_no:
    if float(data) > 3:
        num_rainy_months  = 1
print(num_rainy_months)

CodePudding user response:

No, it's not necessary to call list(). rainfall_mi.split(",") always returns a list. Since it's already a list, you don't need to convert it again.

CodePudding user response:

I think this is better:

rainfall_mi = "1.65, 1.46, 2.05, 3.03, 3.35, 3.46, 2.83, 3.23, 3.5, 2.52, 2.8, 1.85"
num_rainy_months = 0
rainfall_no = rainfall_mi.split(",")
# ↑ This returns a list and stores it in rainfall_no. 
# raninfall_no is list

for data in rainfall_no:
    if float(data) > 3:
        num_rainy_months  = 1
print(num_rainy_months)

You don't need wrap rainfall_mi.split(",") by list() because it is already a list, and you can use it to do whatever you want to do with the list.

CodePudding user response:

rainfall_mi.split(",") creates a list. If you uncomment your other example, you can verify

rainfall_no = rainfall_mi.split(",")
print(type(rainfall_no))

You don't really even need to assign this list to anything. Do the split in the for loop

for data in rainfall_mi.split(","):
    if float(data) > 3:
        num_rainy_months  = 1

And if you want to go full-pythonic, forget the for loop and turn it into a generator to pass to sum

num_rainy_months = sum(float(rainfall) > 3.0 for rainfall in rainfall_mi.split(",")]
  • Related