Given the data for the row index to be found as max_sw and list is sw_col.
I tried this and some other variation, but nothing worked.
print(i for i in range(len(sw_col)) if sw_col[i]== max_sw)
The line you have is almost there. If you put the generator into a list and use only index position zero, this will give you the correct answer:
sw_col = ['a','b','c']
max_sw = 'c'
print([i for i in range(len(sw_col)) if sw_col[i]== max_sw][0]) # prints 2
A more concise solution would be to look up the item directly in the list, like so:
sw_col = ['a','b','c']
max_sw = 'c'
print(sw_col.index(max_sw)) # prints 2
Related
I have a bunch of SQL rows that I have converted to lists:
cursor = conn.cursor()
result = cursor.execute(SQLqueries.sql_qry1)
for row in result:
row_to_list = list(row)
print(row_to_list)
The output of this is lists like:
['FreqBand,Frequency,0, 5, 10\r\n1,0.006,16.56,25.15,30.96\r\n']
['FreqBand,Frequency,0, 5, 10\r\n1,0.006,12.56,15.27,31.90\r\n']
['FreqBand,Frequency,0, 5, 10\r\n1,0.006,16.36,25.15,34.46\r\n']
I would like to edit these lists to exclude the first two words and replace the "\r\n" characters with commas. I've tried this to get rid of the 'FreqBand,Frequency':
for row in result:
row_to_list = list(row)
i = 0
for each in row_to_list:
row_to_list[i].replace('FreqBand', '')
i += 1
print(row_to_list)
but the output of this seems to get rid of half the first list and doesn't edit any of the others. Any help on this would be appreciated.
You need to assign the result of replace() back to the list element. And use range() to get a sequence of numbers instead of incrementing i yourself.
for row in result:
row_to_list = list(row)
for i in range(len(row_to_list)):
row_to_list[i] = row_to_list[i].replace('FreqBand,Frequency,', '').replace('\r\n', ',')
print(row_to_list)
First of all, the list below has a size of 1 rather than 8-10 that I assumed when I first saw the question. So initially, please check if that is something you are aware of.
['FreqBand,Frequency,0, 5, 10\r\n1,0.006,16.56,25.15,30.96\r\n']
In this way, when you iterate over this list with for each in row_to_list:, all you will get is the string that has no difference from the string you would get with row_to_list[0].
Secondly, you might want to double check what you are trying to accomplish with the counter i. In the case of manipulating first elements of each list you name as row_to_list, all you need to do is to access by index then reassign the variable.
for row in result:
row_to_list = list(row)
row_to_list[0] = row_to_list[0].replace('FreqBand,Frequency,', '')
row_to_list[-1] = row_to_list[-1].replace('\r\n', ',')
I am trying to get the sum of x in this type of list: myList=[[y,x],[y,x],[y,x]
Here is my code I have been trying:
myLists = [['0.9999', '2423.99000000'], ['0.9998', '900.00000000'], ['0.9997', '4741.23000000'], ['0.9995', '6516.16000000'], ['0.9991', '10.01000000'], ['0.9990', '9800.00000000']]
if chckList(myLists):
floatList = []
listLength = len(acceptibleBids)
acceptibleBids0 = list(map(float, acceptibleBids[0]))
acceptibleBids1 = list(map(float, acceptibleBids[1]))
floatList.append(acceptibleBids0)
floatList.append(acceptibleBids1)
sumAmounts = sum(amount[1] for amount in floatList)
print(sumAmounts)
print(acceptibleBids)
I have run into many problems, but my current problem are listed below:
1. This list is the way I receive it, so the fact that they are all strings I have been trying to change them to floats so that I can the the sum(myList[1]) of each list inside myList.
2. The list ranges from 1 to 100
You can use list comprehension:
total = sum([float(x[1]) for x in myLists])
print(total) # 24391.39
This should do:
sum = 0
for pair in myLists:
sum+= float(pair[1])
#of course, if there is something that can't
#be a float there, it'll raise an error, so
#do make all the checks you need to make
I'm unsure where acceptibleBids comes from in that code, but I'll assume it is a copy of myList, or something similar to it. The problem with your code is that acceptibleBids[0] is just ['0.9999', '2423.99000000']. Similarly, acceptibleBids[1] is just ['0.9998', '900.00000000']. So when end up with acceptibleBids0 as [[0.9999, 2423.99000000]] and acceptibleBids1 is similarly wrong. Then this makes floatList not be what you wanted it to be.
Edit: list comprehension works too, but I kinda like this way of looking at it. Either way, with list comprehension this would be sum_floats = sum(float([pair[1]) for pair in myLists]).
The following will do:
>>> sum([float(x[0]) for x in myLists])
5.997
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)
If I want to define a function called match_numbers, which would match the area code from one list to the phone number of another list, how should I fix my code? For example:
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
would give me
(666)313-2534
(332)123-3332
My code is:
def phone (nlist, nlist1):
results = {}
for x in nlist1:
results.setdefault(x[0:3], [])
results[x[0:3]].append(x)
for x in nlist:
if x in results:
print(results[x])
The problem with this code is, however:
It gives me the outputs in brackets, whereas I want it to print
the output line by line like shown above, and
it won't work with the parantheses in the 2nd list (for example
(666)543-2322 must be converted as 666-543-2322 for the list to
work.
Now, there are better/faster approaches to do what you are trying to do, but let us focus on fixing your code.
The first issue you have is how you are slicing your string. Remember that you start at index 0. So if you do:
x[0:3]
What you are actually getting is something like this from your string:
(12
Instead of your intended:
123
So, knowing that indexes start at 0, what you actually want to do is slice your string as such:
x[1:4]
Finally, your line here:
results[x[0:3]].append(x)
There are two problems here.
First, as mentioned above, you are still trying to slice the wrong parts of your string, so fix that.
Second, since you are trying to make a key value pair, what that above line is actually doing is making a key value pair where the value is a list. I don't think you want to do that. You want to do something like:
{'123': '(123)5556666'}
So, you don't want to use the append in this case. What you want to do is assign the string directly as the value for that key. You can do that as such:
results[x[1:4]] = x
Finally, another problem that was noticed, is in what you are doing here:
results.setdefault(x[1:4], [])
Based on the above explanation on how you want to store a string as your value in your dictionary instead of a list, so you don't need to be doing this. Therefore, you should simply be removing that line, it does not serve any purpose for what you are trying to do. You have already initialized your dictionary as results = {}
When you put it all together, your code will look like this:
def match_phone(nlist, nlist1):
results = {}
for x in nlist1:
results[x[1:4]] = x
for x in nlist:
if x in results:
print(results[x])
match_phone(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
And will provide the following output:
(666)313-2534
(332)123-3332
If all the phone numbers will be in the format (ddd)ddd-dddd you can use
for number in (num for num in nlist1 if num[1:4] in nlist):
print(number)
You could use some better variable names than nlist and nlist1, in my view.
def match_phone(area_codes, numbers):
area_codes = set(area_codes)
for num in numbers:
if num in area_codes:
print num
You could do something like this:
phone_numbers = ['(443)241-1254', '(666)313-2534', '(332)123-3332']
area_codes = ['666', '332']
numbers = filter(lambda number: number[1:4] in area_codes, phone_numbers)
for number in numbers:
print(number)
Another similar way to do this without using a filter could be something like this:
for number in phone_numbers:
if number[1:4] in area_codes:
print(number)
Output in either case would be:
(666)313-2534
(332)123-3332
No one with regex solution! This may be an option too.
import re
def my_formatter(l1,l2):
mydic = {re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(2):re.match(r'([(])([0-9]+)([)])([0-9]+[-][0-9]+)',i).group(4) for i in l2}
for i in l1:
print "({0}){1}".format(str(i),str(mydic.get(i)))
my_formatter(['666', '332'], ['(443)241-1254', '(666)313-2534', '(332)123-3332'])
It prints-
(666)313-2534
(332)123-3332
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!