Python Forum
Looping through an if/else statement
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Looping through an if/else statement
#1
Hi,
I have been struggling with getting an if/else statement working in Python 2.7. I have searched for a couple of days (on and off) throughout several online forums for the answer, as well as have reviewed other pieces of similar code that has been posted online by the developer of the package I am working with. I have also tried to briefly review the examples of if/else statements on various Python tutorials. Unfortunately, no one in my current work environment works with Python.

I think what I am trying to do is loop through a list of names to plot species names in the list one colour, and those not on the list another.

This following code works when there is only species

colorlist = ["#B2182B" if "SchEpi6" in tip else "#000000" for tip in rtre.get_tip_labels()]
In this example, I am specifying that I want the species named "SchEpi6" plotted in burgundy and all of the other species in rtre.get_tip_labels() in black. This 'colorlist' is then entered into a function that draws a phylogeny (a diagram that shows the evolutionary relationships among species) for a set of focal species.

I would like to have several different tips coloured burgundy. Examples of what I have tried include:

colorlist = ["#B2182B" if ("SchEpi6", "SchEpi2) in tip else "#000000" for tip in rtre.get_tip_labels()]
splist = ["SchEpi6", 
"SchEpi2]
colorlist = ["#B2182B" if "splist" in tip[i] else "#000000" for tip in rtre.get_tip_labels()]
When I do get the code to work, it either turns everything black or burgundy, but I have never got two tips (for example - "SchEpi6" and "SchEpi2") to plot out in a burgundy, with the remainder of the phylogeny's tip remaining black. What would be the best way to do this?

How could I then incorporate a second, third, etc. list of species and designate them different colours?

Thanks for your time.
Reply
#2
You need two loops. Loop through the labels. Within that loop, set the color to white, loop through the species, and if any species matches, change the color to burgundy and break out of the inner loop.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020