Access an element in a list of lists in python - python

I am new to python and am trying to access a single specific element in a list of lists.
I have tried:
line_list[2][0]
this one isn't right as its a tuple and the list only accepts integers.
line_list[(2, 0)]
line_list[2, 0]
This is probably really obvious but I just can't see it.
def rpd_truncate(map_ref):
#Munipulate string in order to get the reference value
with open (map_ref, "r") as reference:
line_list = []
for line in reference:
word_list = []
word_list.append(line[:-1].split("\t\t"))
line_list.append(word_list)
print line_list[2][0]
I get the exact same as if I used line_list[2]:
['Page_0', '0x00000000', '0x002DF8CD']

actually split will return a list
more over you don't require word_list variable
for line in reference:
line_list.append(line[:-1].split("\t\t"))
print line_list[2][0]

Related

How to use a list comprehension to read from a function and create a new list?

Using list comprehension to extract all the tweets in the tweets_and_more list and save them in another list called tweets. Print the length of the resulting list. Also, print the first three elements of the new list.
start_tag = "<tweet>"
def extract_tweet(data):
start = data.index("<tweet>")+len(start_tag)
end = data.index("</tweet>")
seq = data[start:end]
return seq
This is my extract tweet function
My list with all the tweets line by line is saved in a list called "tweets_and_more"
I'm having a hard time figuring out how to use List compression to do this. I can do it using a loop I guess but any help with explanation would be great.
The for loop code is placed at the end
tweets = [extract_tweet(data) for data in tweets_and_more]

Problem parsing data from a firewall log and finding "worm"

I am struggling with trying to see what is wrong with my code. I am new to python.
import os
uniqueWorms = set()
logLineList = []
with open("redhat.txt", 'r') as logFile:
for eachLine in logFile:
logLineList.append(eachLine.split())
for eachColumn in logLineList:
if 'worm' in eachColumn.lower():
uniqueWorms.append()
print (uniqueWorms)
eachLine.split() returns a list of words. When you append this to logLineList, it becomes a 2-dimensional list of lists.
Then when you iterate over it, eachColumn is a list, not a single column.
If you want logLineList to be a list of words, use
logLineList += eachLine.split()
instead of
logLineList.append(eachLine.split())
Finally, uniqueWorms.append() should be uniqueWOrms.append(eachColumn). And print(uniqueWorms) should be outside the loop, so you just see the final result, not every time a worm is added.

How to compare inside list values in python

I have to find 6 distincts words in a bunch of lists. For example in first list, there will be word 'me', in second word 'us'.
I've already found the line number using this code:
def creatList(file):
try:
for i,line in enumerate(file,1):
and pass found values to another function,
line=(line.rstrip()).split()
rawList=[]
rawList.append(line)
creatRuleFile(i,rawList)
inside that function,
def creatRuleFile(p,new):
print(new)
print("{0}. {1}".format(p, new))
lookup ='me'
if p==1:
print('found at line:', lookup)
my code is not working as I want... appreciate if you can suggest an answer. Thank you.
Has been answered before:
Python: Find in list
use something like
stuff_I_want_to_find = "whatever"
if stuff_I_want_to_find in myList:
index = myList.find(stuff_I_want_to_find)
now you have to iterate over your lists and over your words, which will essentially be two loops.

TypeError: list indices must be integers, not str - loading strings from a list

So I have a list of strings I want to make = 999
with open ("Inventory.txt", 'r') as i:
for items in i:
item = GetItemID(items)
PositionOfItems[items]=HERO_INVENTORY_POS
HERO_INVENTORY_POS is = 999, but I get the error displayed above, if I'm missing anything else require please tell me.
This is the code I used for spawning an item so I kinda just tried to recreate that.`
ItemRequest = input("Which item would you like?").upper()
for i in ItemList:
if i == ItemRequest:
ItemRequest = GetItemID(ItemRequest)
PositionOfItems[ItemRequest]=HERO_INVENTORY_POS`
If PositionOfItems is a list, then items needs to be in an integer. Right now, it's a string, because you're reading it from a file.
Try:
PositionOfItems[int(items)]=HERO_INVENTORY_POS
Alternatively, maybe you intended to index the list with item and not items? In which case you should do
PositionOfItems[item]=HERO_INVENTORY_POS
Depending in how you defined PositionOfItems
In your line of code
PositionOfItems[items]=HERO_INVENTORY_POS
You are treating it as a dictionary instead of a list, where items is the key and HERO_INVENTORY_POS is the value. When I tried reproducing your code snippet(below), my error was that the dictionary was not defined as empty before its use, and if defined as a list I received the TypeError: list indices must be integers, not str.
with open("test.txt", 'r') as f:
dict = {} #This line
for item in f:
dict[item] = 999
print item,
If you have assigned PositionOfItems as a list, then the issue is that you would be referring to indexes that have not been defined (or at least not show in your code here) and are attempting to reference them with a string (items) instead of an integer. (Giving you the TypeError)

use slice in for loop to build a list

I would like to build up a list using a for loop and am trying to use a slice notation. My desired output would be a list with the structure:
known_result[i] = (record.query_id, (align.title, align.title,align.title....))
However I am having trouble getting the slice operator to work:
knowns = "output.xml"
i=0
for record in NCBIXML.parse(open(knowns)):
known_results[i] = record.query_id
known_results[i][1] = (align.title for align in record.alignment)
i+=1
which results in:
list assignment index out of range.
I am iterating through a series of sequences using BioPython's NCBIXML module but the problem is adding to the list. Does anyone have an idea on how to build up the desired list either by changing the use of the slice or through another method?
thanks zach cp
(crossposted at [Biostar])1
You cannot assign a value to a list at an index that doesn't exist. The way to add an element (at the end of the list, which is the common use case) is to use the .append method of the list.
In your case, the lines
known_results[i] = record.query_id
known_results[i][1] = (align.title for align in record.alignment)
Should probably be changed to
element=(record.query_id, tuple(align.title for align in record.alignment))
known_results.append(element)
Warning: The code above is untested, so might contain bugs. But the idea behind it should work.
Use:
for record in NCBIXML.parse(open(knowns)):
known_results[i] = (record.query_id, None)
known_results[i][1] = (align.title for align in record.alignment)
i+=1
If i get you right you want to assign every record.query_id one or more matching align.title. So i guess your query_ids are unique and those unique ids are related to some titles. If so, i would suggest a dictionary instead of a list.
A dictionary consists of a key (e.g. record.quer_id) and value(s) (e.g. a list of align.title)
catalog = {}
for record in NCBIXML.parse(open(knowns)):
catalog[record.query_id] = [align.title for align in record.alignment]
To access this catalog you could either iterate through:
for query_id in catalog:
print catalog[query_id] # returns the title-list for the actual key
or you could access them directly if you know what your looking for.
query_id = XYZ_Whatever
print catalog[query_id]

Categories

Resources