BVCN
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Lesson 3 Python THEME - ARRAY of taxonomy + data columns string slicing --> list slicing pop index strings -> lists (split) slicing substrings from the list pop index & negative indices examples from a list and string enumerate sort - in reference to original vs how numbers and strings sort(reverse=True) extend tax_string = "d__Bacteria; p__Proteobacteria; c__Alphaproteobacteria; o__Rhizobiales; f__Xanthobacteraceae; g__Bradyrhizobium; s__Bradyrhizobium canariense_A" parameters = ["Sample1", "Sample2", "Nitrogen1", "Nitrogen2"] data_values = [0.4, 5.0, 1.2, 1.4] 1. string that is taxonomy string 3. manipulate list/string functions 5. list numerals --> dictionary Sample1 | Type Strain Cnt | nitrogen content 6. convert lists to dictionary 7. introduce second organisms and make of dictionary of dictionaries 8. Either convert dict to array OR from multiple inputs create an array 9. Array stuff ```python ``` ## Lists & Strings Lists hold indexed data with each indexed datum separated by a ','. Declaring a dataset as a list can be done by enclosing in '[]' or 'list()'. For example, a list of strings might look like ['a', 'b', 'c']. You may notice similarities between string structures and indices and lists. This is because strings are treated as lists of characters in python. A common first task in many bioinformatics analyses is cleaning up strings- whether it be sequences or taxonomy information. Below, will will remove empty spaces from tax_string. For our analyses, we are only interested in the taxonomic information down to the order level. So, we will select a substring up to that point by finding "o__". Finally, we will remove all of the taxonomic level indicators. ```python tax_string = "d__Bacteria; p__Proteobacteria; c__Alphaproteobacteria; o__Rhizobiales; f__Xanthobacteraceae; g__Bradyrhizobium; s__Bradyrhizobium canariense_A"` tax_string.strip() ``` Notice that if we try to clean up all the white spaces in tax_string it does NOT work. This is because strip specifically only cleans up the specified characters from the leading and trailing ends of a string. Let's try again using another method. ```python tax_string=tax_string.replace(' ','') ``` Using the string .replace() method, we can have each space character 'replaced' with no characters (in other words, deleting).Notice that I have to set tax_string equal to itself to overwrite the original variable. Otherwise, tax_string will not be modified. Now let's retreive all the taxonomic information down to the order level. We will do this by using the string .find() method to locate '__f', which is the classification level after order. Then we will using string indexing to retrieve what we want. ```python orderEndInd=tax_string.find(';__f') print(orderEndInd) ``` Notice when the variable orderEndInd is printed, it is a number. This number is the index of the first character of entire substring ';__f' in tax_string. Now we are going to slice the string to include all characters from the beginning of tax string up to (not including)';__f' ```python order_tax_string=tax_string[:5] order_tax_string=tax_string[:orderEndInd] ``` STRING |S|T|R|I|N|G| 0S1T2R3I4N5G6 TAXONOMY Notice that the indices for character positions are enclosed in []. In this case, I have used the short hand ':' as one of my indices. When this precedes an index, it means to retrieve all characters from the beginning of that string up to (but not including) the index. When it comes after an index, it means to retrieve all characters from that index through the end of the string. order_tax_string will be the taxonomy for all 4 entries in our other lists of associated data. So, now, lets make a list called 'tax_list' populated with order_tax_string 4 times. ```python tax_list=[order_tax_string]*4 ``` If you print tax_list, notice that tax list is compromised of the string order_tax_string 4 times, with each list entry separated by a comma. You can pull any specific entry from the list by it's index, or slice it by using indices, the same way as you would a string. For example ```python tax_list[2:] ``` will pull items from the list starting at index 2 through the end of the list. But, CAREFUL. While the start index begins at that index, if you were to include an end index, you will pull up to but NOT including that index. For example: ```python tax_list[1:3] ``` will include indexed items 1 and 2, not 1, 2,and 3. More often then not, we are interested in the relationship between items in multiple lists rather than using a single list. If two lists of related items are ordered the same way, we can iterate through them in parallel to further sort our data. To iterate through two lists in parllel, we can use zip(). ``` for sample, datum in zip(parameters, data_values): print(sample, datum) ``` Using this syntax, sample and datum are the respective individual items in the lists parameters and data_values Let's say I wanted to only work with samples that had data values between 1 and 2. ``` newParams=[] newDataValues=[] for sample, datum in zip(parameters, data_values): if datum >= 1 and datum <=2: print('sample:',sample,'\n datum:',datum) newParams.append(sample) newDataValues.append(datum) ``` I have declared two empty lists- newParams and newDataValues. Using this loop structure, i am iterating through the lists parameters and data_values in parallel. Only sample names and their corresponding data values that meet the condition in the if statement will be printed. Then, they will be added to their new lists. Let's check out our filtered data sets using some built-in functions. ``` print(len(newParams)) ``` will print the length of the newParams list. ``` print(newParams[-1]) ``` will print the last item in the newParams list. The index -1 in pyton will always return the last item in a list. Let's say that we wanted our lists arranged in descending data_value order (greatest to least) using the .sort() python function.This function alters the list in place. So, if we want to preserve the original indexing, we need to make a copy of the list first. ``` unsortedDataValues=newDataValues.copy() newDataValues.sort(reverse=True) ``` Now our data list is sorted in descending value. However, we need to reorder the corresponding newParams list to be in the correct order. For each element in sortednewDataValues, we need to find the corresponding element in newDataValues and its index. We can use list indexing to do this. Let's iterate through the sorted newDataValues, find the index of each element in unsortedDataValues, and use that to grab the corresponding element in newParams. ``` sortedNewParams=[] for val in newDataValues: oldListInd=unsortedDataValues.index(val) param=newParams[oldListInd] sortedNewParams.append(param) ``` Let's print each item from our sorted lists and see if they are sorted properly. ``` for sample, datum in zip(sortedNewParams, newDataValues): print('sample: ',sample) print('datum: ', datum,'\n') ``` As we can see from comparing to our original lists, this is the correct order. Now we can iterate through our shortened, sorted lists and turn them in to a list of sample:datum tuples, or pairs in the format (item1,item2), so they can be converted into a dictionary. ``` sdTupleList=[] for sample, datum in zip(sortedNewParams, newDataValues): sdTuple=(sample,datum) sdTupleList.append(sdTuple) print(sdTupleList) ``` Notice that all of our data is now in sample,datum pairs. This can easily be converted into a dictionary by ``` sdDict=dict(sdTupleList) ``` ## Dictionaries Dictionaries hold key-value pairs in a mutable data format - meaning that we can provide things like "Chicago":"deep dish", "New York":"thin crust" and then recall elements that are related to each other. For science we may have a parameter name `Sample 1` and want to store the value associated with Sample 1. For the example above, ```python parameters = ["Sample1", "Sample2", "Nitrogen1", "Nitrogen2"] data_values = [0.4, 5.0, 1.2, 1.4] ``` There are many ways to initialize a dictionary. 1. We can call a empty dictionary and fill it with each elements ```python dict1 = {} dict1 = {"Sample1":0.4, "Sample2":5.0, "Nitrogen1":1.2, "Nitrogen2":1.4} ``` 2. We can take a list of tuples and convert it to a dictionary with the `dict()` function ```python list1 = [("Sample1",0.4), ("Sample2",5.0), ("Nitrogen1",1.2), ("Nitrogen2",1.4)] dict2 = dict(list1) ``` ```python print(dict1) print(dict2) ``` Dictionaries display their content based on how it was defined, but the information is not stored by numerical index like in a list. ### Accessing Contents in a Dictionary Recovering elements from a dictionary is based on the key and value terms If you tried to call the "second" element of a dictionary in the same way as a list - it will result in an error ```python dict1[1] ``` We still use brackets to denote what we are trying to call, however, by asking for the second element like in a list it does not work Instead, we use the key to produce the value ```python dict1["Sample1"] ``` It is importanat for the key to be in the correct format. As the key is a string we need to provide a string. We can use this formating to `add`, `modify`, & `delete` elements Add ```python dict1["Sample3"] = 4.1 ``` Modifty ```python dict1["Sample3"] = 3.7 ``` Delete ```python del dict1["Sample3"] ``` We can use this method to build a dictionary incrementally. One element at a time. There are a few rules about keys - they can only be be immutable data types * includes str, int, float, bool * excludes tuples, lists, dicts Values can be anything, including objects like lists and more dictionaries! ```python dict3 = {} dict3["Sample1"] = 3.1 dict3["Phosphorous1"] = 0.5 dict3[0] = "Time" dict3[13] = "Date" print(dict3) ``` ```python dict3["Phosphorous1"] dict3["Phosphorous1"] = 1 dict3[0] ``` Why do I successfully return an value here? Dictionaries do not use index numbering, BUT `0` is a key in my dictionary ```python dict3[1] dict3[13] ``` Here's an example of a dictionary within a dictionary ```python dict4 = {"Bacillus":{"Sample1":0.4, "Sample2":5.0, "Nitrogen1":1.2, "Nitrogen2":1.4}, "Roseburia":{"Sample1":1.6, "Sample2":2.0, "Nitrogen1":1.0, "Nitrogen2":1.8}} dict4["Bacillus"] dict4["Roseburia"] #To call specific items within the second dictionary, we need 2 key values dict4["Roseburia"]["Sample1"] ``` ### Operators and Built-in Functions We can ask if a certain value is present in a dictionary with `in` and `not in` ```python print(dict1) "Sample1" in dict1 "Sample1" not in dict1 "Sample5" in dict1 ``` We can use the `len()` function to return the number of keys in a dictionary ```python len(dict1) len(dict4) len(dict4["Bacillus"]) ``` #### clear() You can empty a dictionary using `clear()` ```python print(dict3) dict3.clear() print(dict3) ``` #### get(<key\>) `get()` searches a dictionary for a key and either returns the value or the if not present returns `None`. This allows you to check for a check without asking if it is `in` or `not in`. You can also set the returned value to something meaningful to your data. ```python print(dict1.get("Sample1")) print(dict1.get("Sample5")) print(dict1.get("Sample1", -1)) ``` #### items() `item()` returns a list of tuples with (key,value) pairs ```python list(dict1.items()) ``` #### keys() `keys()` returns a list of keys in the dictionary. This can be incredibly useful in the future in `for loops` to process items witin the dictionary ```python dict1.keys() ``` #### values() `values()` works like `key()` but returns the values as a list not the keys. Multiple `values` with the same value will be returned individually in the list ```python dict1.values() dict5 = {1:10, 2:10, 3:10} dict5.values() ``` #### pop() `pop()` removes a key-value pair from a dictionary using the key and returns the value ```python dict5.pop(1) dict4.pop("Roseburia") dict4.pop("Faecalibacterium") dict4.pop("Faecalibacterium", -1) ``` #### popitem() `popitem()` removes a key-value pair from a dictionary using the key and returns a tuple ```python dict2.pop() dict2.pop("Sample2") ``` #### update() `update()` merges dictionaries or key-value pairs with an existing dictionary ```python dict6 = {'a':10, 'b':9, 'c':3} dict7 = {'d':11, 'e':5} dict6.update(dict7) dict6 ``` key-value pairs added as a list of tuples ```python dict6.update([('d',11), ('e', 5)]) dict6 ``` key-value pairs added as a list of arguments ```python dict6.update(d=11, e=5) dict6 ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully