I am trying to print multiple items from a list in Python. I have looked at many examples but I am unable to get them to work. What is a good way to print items from the imported list based on their list index.
The commented out example in my code is what I thought will work and cant find a simple solution.
items = []
with open('input.txt') as input_file:
for line in input_file:
items.append(line)
print(items[5],items[6])
#print(items[5,6,7]
One way to do it would be with a for loop.
item_list = ['a','b','c','d','e','f','g','i'] # an example list.
index_to_print = [5,6,7] # add all index you want to print to this list.
for i in item_list:
if item_list.index(i) in index_to_print:
print(i)
update: instead of looping through the whole item_list, we can loop through the indexes you want to print.
for i in index_to_print:
if i < len(item_list):
print(item_list[i])
else:
print('given index is out of range.')
Related
New to python and for this example list
lst = ['<name>bob</name>', '<job>doctor</job>', '<gender>male</gender>', '<name>susan</name>', '<job>teacher</job>', '<gender>female</gender>', '<name>john</name>', '<gender>male</gender>']
There are 3 categories of name, job, and gender. I would want those 3 categories to be on the same line which would look like
<name>bob</name>, <job>doctor</job>, <gender>male</gender>
My actual list is really big with 10 categories I would want to be on the same line. I am also trying to figure out a way where if one of the categories is not in the list, it would print something like N/A to indicate that it is not in the list
for example I would want it to look like
<name>bob</name>, <job>doctor</job>, <gender>male</gender>
<name>susan</name>, <job>teacher</job>, <gender>female</gender>
<name>john</name>, N/A, <gender>male</gender>
What would be the best way to do this?
This is one way to do it. This would handle any length list, and guarantee grouping no matter how long the lists are as long as they are in the correct order.
Updated to convert to dict, so you can test for key existence.
lst = ['<name>bob</name>', '<job>doctor</job>', '<gender>male</gender>', '<name>susan</name>', '<job>teacher</job>', '<gender>female</gender>', '<name>john</name>', '<gender>male</gender>']
newlst = []
tmplist = {}
for item in lst:
value = item.split('>')[1].split('<')[0]
key = item.split('<')[1].split('>')[0]
if '<name>' in item:
if tmplist:
newlst.append(tmplist)
tmplist = {}
tmplist[key] = value
#handle the remaining items left over in the list
if tmplist:
newlst.append(tmplist)
print(newlst)
#test for existance
for each in newlst:
print(each.get('job', 'N/A'))
I was wondering if there is any way to save the first result of a for loop as a variable, and not the last. I wanted to get the first result of searching on youtube, following the code in https://github.com/ytdl-org/youtube-dl. The for loop is something like this,
for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}):
vids = 'https://www.youtube.com' + vid['href']
But I want the first result, not the last.
I guess you want something like this
lst = [1,2,3,4,5]
so you want to get 1, the first element. You can do lst_saved = lst[0]
but if you want to use a loop and get the first element, you could use
for i in lst:
lst_saved = i
break
but that's... awful
You can do something like
test = 0
for i in range(5):
if i == 0:
test = i
Is this what you wanted?
Do you just want the first element, or are you trying to complete the loop then access the first one?
Either way, I'd avoid a loop, and doing something else.
For the former, you can just ignore the rest of the list do something like this since the "list[0]" syntax will just pick out the first item in the list:
what_you_want = 'https://www.youtube.com/' + soup.findAll(attrs={'class':'yt-uix-tile-link'})[0]['href']
Or otherwise, I'd recommend using list concatenation so that you're not overwriting the variable each time you loop. You can achieve the same thing multiple ways, but here's how I'd go:
# first get your list of links
list_of_things = ['https://www.youtube.com/' + vid['href'] for vid in soup.findAll(attrs={'class':'yt-uix-tile-link'}]
# then pick out the first item in your list
what_you_want = list_of_things[0]
How do I add all of the elements in a webpage to a list (array) in python with selenium?
Ive tried things like:
list = driver.find_elements_by_class_name("classname")
list = driver.find_elements(by="class", "classname")
When i print the list after this, it only shows [].
You can print elements from list using the below approach :
list = driver.find_elements_by_class_name("classname")
for item in list:
print (item.text)
What I found out worked, was doing
list_of_elements = driver.find_element_by_xpath('//*[#class="classname"]')
Then I did
names = []
for i in range(len(list_of_elements)):
names.append(list_of_elements[i].text)
Ive been trying to create a part of code that takes data from an excel file then adds it into a list but only once. all other times should be ignored, ive managed to get all the data i need, just need to know how to pop unwanted duplicates. Also wondering if i should do this in a dictionary and how it would be done if i did
for cellObj in rows:<br>
Lat = str(cellObj[5].value)<br>
if 'S' in Lat:<br>
majorCity.append(str(cellObj[3].value))<br>
print(majorCity)<br>
elif majorCity == majorCity:<br>
majorCity.pop(str(cellObj[3].value))<br>
You can use set(), it will remove duplicates from a sequence.
a= set()
a.add("1")
a.add("1")
print a
Output:
set(['1'])
set is indeed a good way to do this:
>>> my_list = [1,1,2,2]
>>> my_list_no_dups = list(set(my_list))
>>> my_list_no_dups
[1, 2]
but it will not necessarily preserve the order of the list. If you do care about the order, you can do it like this:
my_list_no_dups = []
for item in my_list:
if item not in my_list_no_dups:
my_list_no_dups.append(item)
Am I able to slice a list of strings? If it is possible could anyone please tell me how to do it so that I am able to print out a particular string instead of the five that make up the list.
Cheers.
eg.
mylist = ['apples' 'oranges' 'lemons' 'cucumbers' 'bananas']
print 'orange'
** The programming language i am using is python. Every time I code it mylist[2] it comes out as an error. The list I am using is extracting the strings from a html rss feed. Each string is a new news heading. However, even when it updates constantly there are always 5 strings in the list and it tells me list index out of range. But if I just print the entire list it works fine**
#URLS for RSS Feeds
url_national = 'http://feeds.news.com.au/public/rss/2.0/news_national_3354.xml'
url_sport = 'http://feeds.news.com.au/public/rss/2.0/news_sport_3168.xml'
url_world = 'http://feeds.news.com.au/public/rss/2.0/news_theworld_3356.xml'
url_technology = 'http://feeds.news.com.au/public/rss/2.0/news_tech_506.xml'
def headlines (url):
web_page = urlopen(url)
html_code = web_page.read()
web_page.close()
return findall(r'<item><title>([^<]*)</title>', html_code)
#headlines list
list_national = [headlines(url_national)]
list_sport = [headlines(url_sport)]
list_world = [headlines(url_world)]
list_technology = [headlines(url_technology)]
def change_category():
if label_colour.get() == 'n':
changeable_label['text'] = list_national #here I would slice it but it doesn't work
elif label_colour.get() == 's':
changeable_label['text'] = list_sport
elif label_colour.get() =='w':
changeable_label['text'] = list_world
else:
changeable_label['text'] = list_technology
the reason I need to slice it into individual heading is so when the radio button is pressed for my GUI it prints them in a numbered list on the label not all just running on one line next to them - sorry i hope that makes sense
What language are you using here? Usually you can use an index to access a particular entry in a list. For example:
print myList[1]
Commas are missing in your list creation. You have to do it like this:
mylist = ['apples', 'oranges', 'lemons', 'cucumbers', 'bananas']
And you will be able to work with your list
mylist[0] # 'apples'
mylist[-1] # 'bananas'
mylist[2] # 'lemons'
I think the error you are getting is something like this:
mylist = ['apples' 'oranges' 'lemons' 'cucumbers' 'bananas']
print mylist[5]
IndexError: list index out of range
The reason is the elements in a list are indexed from 0 not 1.
The mylist has 5 elements starting from 0 to 4. So when you call print mylist[5] it will definitely give an error as there is no 6th element in the list.
Here is the official doc regarding list please have a look.
I hope it was helpful!