Ad
Want Create A New List From Existing List Using If Else Statement
I want to create a new list using existing list "dta", where i do not want a value for "banana" but a numeric for others. desired list is below:
[1,3,4,5,6]
but when i am trying to print of my final list "d" then i get only single value.
dta=list(["apple","banana","pine","cucumber","Guava","Coconut"])
d=[]
def cont_list(x):
for i in x:
if i=="banana":
continue
if i=="pine":
d.append(3)
elif i=="apple":
d.append(1)
elif i=="cucumber":
d.append(4)
elif i=="Guava":
d.append(5)
else:
d.append(6)
return d
cont_list(dta)
print(d)
Ad
Answer
you can do it with list comprehension:
dta = ["apple","banana","pine","cucumber","Guava","Coconut"]
d = [idx for idx in range(1,len(dta)+1) if dta[idx-1] != "banana"]
print (d)
in function:
dta=list(["apple","banana","pine","cucumber","Guava","Coconut"])
def cont_list(x):
dta = ["apple","banana","pine","cucumber","Guava","Coconut"]
d = [idx for idx in range(1,len(dta)+1) if dta[idx-1] != "banana"]
return d
print (cont_list(dta))
output:
[1, 3, 4, 5, 6]
NOTE: your code will be ok if you fix INDENTION:
d=[]
def cont_list(x):
for i in x:
if i=="banana":
continue
if i =="pine":
d.append(3)
elif i=="apple":
d.append(1)
elif i=="cucumber":
d.append(4)
elif i=="Guava":
d.append(5)
else:
d.append(6)
return d
cont_list(dta)
print(d)
or you can do it like:
d=[]
def cont_list(x):
for i in range(len(x)):
if x[i]=="banana":
continue
else:
d.append(i+1)
return d
cont_list(dta)
print(d)
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad