build a set of values in dictionary - python-3.x

I've been scratching my head over this problem for a couple of days and i feel my vision a bit tunneled right now, so i thought maybe you can shed some light on this matter :)
so this app runs some code, gets some values till it gets to this part:
for y in query2:
del list2[:]
list2.append(y.share_with)
data[x]=print(list2)
data is a dictionary, and the keys 'x' are being added correctly to the dictionary but as you have guessed the problem is with list2.
i want to add a set of values (returned from query2) to each 'x' key,
i thought to initialize the list2 outside the loop empty it on each iteration and store it in the dictionary but that doesn't work obviously.
Any ideas would be much appreciated :)
EDIT:
That's the code that works:
for x in output:
query2 = oc_share.select(oc_share.share_with).where(oc_share.file_target == x)
list2 = []
for y in query2:
list2.append(y.share_with)
data[x]=print(list2)
Many thanks

EDIT:
That's the code that works:
for x in output:
query2 = oc_share.select(oc_share.share_with).where(oc_share.file_target == x)
list2 = []
for y in query2:
list2.append(y.share_with)
data[x]=print(list2)

Related

comparing int value in list throws index out of range Error

I'm struggling to grasp the problem here. I already tried everything but the issue persist.
Basically I have a list of random numbers and when I try to compare the vaalues inside loop it throws "IndexError: list index out of range"
I even tried with range(len(who) and len(who) . Same thing. When put 0 instead "currentskill" which is int variable it works. What I don't understand is why comparing both values throws this Error. It just doesn't make sence...
Am I not comparing a value but the index itself ???
EDIT: I even tried with print(i) / print(who[i] to see if everything is clean and where it stops, and I'm definitelly not going outside of index
who = [2, 0, 1]
currentskill = 1
for i in who:
if who[i] == currentskill: # IndexError: list index out of range
who.pop(i)
The problem is once you start popping out elements list size varies
For eg take a list of size 6
But you iterate over all indices up to len(l)-1 = 6-1 = 5 and the index 5 does not exist in the list after removing elements in a previous iteration.
solution for this problem,
l = [x for x in l if x]
Here x is a condition you want to implement on the element of the list which you are iterating.
As stated by #Hemesh
The problem is once you start popping out elements list size varies
Problem solved. I'm just popping the element outside the loop now and it works:
def deleteskill(who, currentskill):
temp = 0
for i in range(len(who)):
if who[i] == currentskill:
temp = i
who.pop(temp)
There are two problems in your code:
mixing up the values and indexes, as pointed out by another answer; and
modifying the list while iterating over it
The solution depends on whether you want to remove just one item, or potentially multiple.
For removing just one item:
for idx, i in enumerate(who)::
if i == currentskill:
who.pop(idx)
break
For removing multiple items:
to_remove = []
for idx, i in enumerate(who)::
if i == currentskill:
to_remove.append[idx]
for idx in reversed(to_remove):
who.pop(idx)
Depending on the situation, it may be easier to create a new list instead:
who = [i for i in who if i != currentskill]
Your logic is wrong. To get the index as well as the value, use the built-in function enumerate:
idx_to_remove = []
for idx, i in enumerate(who)::
if i == currentskill:
idx_to_remove.append[idx]
for idx in reversed(idx_to_remove):
who.pop(idx)
Edited after suggestion from #sabik

Math-like way to define a set in Python: technical name [duplicate]

Can someone explain the last line of this Python code snippet to me?
Cell is just another class. I don't understand how the for loop is being used to store Cell objects into the Column object.
class Column(object):
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = [Cell(self, i) for i in xrange(region.cellsPerCol)] #Please explain this line.
The line of code you are asking about is using list comprehension to create a list and assign the data collected in this list to self.cells. It is equivalent to
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
Explanation:
To best explain how this works, a few simple examples might be instructive in helping you understand the code you have. If you are going to continue working with Python code, you will come across list comprehension again, and you may want to use it yourself.
Note, in the example below, both code segments are equivalent in that they create a list of values stored in list myList.
For instance:
myList = []
for i in range(10):
myList.append(i)
is equivalent to
myList = [i for i in range(10)]
List comprehensions can be more complex too, so for instance if you had some condition that determined if values should go into a list you could also express this with list comprehension.
This example only collects even numbered values in the list:
myList = []
for i in range(10):
if i%2 == 0: # could be written as "if not i%2" more tersely
myList.append(i)
and the equivalent list comprehension:
myList = [i for i in range(10) if i%2 == 0]
Two final notes:
You can have "nested" list comrehensions, but they quickly become hard to comprehend :)
List comprehension will run faster than the equivalent for-loop, and therefore is often a favorite with regular Python programmers who are concerned about efficiency.
Ok, one last example showing that you can also apply functions to the items you are iterating over in the list. This uses float() to convert a list of strings to float values:
data = ['3', '7.4', '8.2']
new_data = [float(n) for n in data]
gives:
new_data
[3.0, 7.4, 8.2]
It is the same as if you did this:
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
This is called a list comprehension.

What does this input via list-comprehension do?

You know when you find a solution via trial and error but you stumbled so much thtat you can't understand the answer now?
Well this is happening to me with this piece:
entr = [list(int(x) for x in input().split()) for i in range(int(input()))]
The input is done by copying and pasting this whole block:
9
8327 0
0070 0
2681 2
1767 0
3976 0
9214 2
2271 2
4633 0
9500 1
What is my list comprehension exactly doing in each step? And taking into account this: How can I rewrite it using for loops?
In fact, your code is not a nested list-comprehension, beause you use list construtor rather than mere list-comprehension.
This line serves as same as your code:
entr = [[int(x) for x in input().split()] for i in range(int(input()))]
To understand this line, you must remember the basic structure of list-comprehension in python, it consists of two component obj and condition with a square brackets surrounding:
lst = [obj condition]
it can be converted to a loop like this:
lst = []
condition:
lst.append(obj)
So, back to this question.
What you need to do now is to break the nested list-comprehension into loop in loop, usually you begin from the condition in latter part, from outer space to inner space. You got:
entr = []
for i in range(int(input())):
entr.append([int(x) for x in input().split()])) # the obj is a list in this case.
And now, you can break the list-comprehension in line 3.
entr = []
for i in range(int(input())):
entry = []
for x in input().split():
entry.append(int(x))
entr.append(entry)
So, now the stuff the original line can be easily understand.
the program construct a entry list named entr;
the program ask for user input and convert the input string into an int, which is the number of the entrys you want to input(assume it is num);
the program ask for user input for num times, each time you should input something seperate with spaces.
The program split every string into a list (named entry in above code) you input with str.split() method (with parameter sep default to space). And append each entry list in every loop.
for every element in the entry list, it converted to int.
My English may be poor, feel free to improve my answer:)
That is equivalent to this:
entr = []
for i in range(int(input())):
row = []
for x in input().split():
row.append(int(x))
entr.append(row)
You can copy-paste that into a list comprehension in a couple steps. First the inner loop/list:
entr = []
for i in range(int(input())):
row = [int(x) for x in input().split()]
entr.append(row)
Without the row variable:
entr = []
for i in range(int(input())):
entr.append([int(x) for x in input().split()])
Then the outer loop/list (copied over multiple lines for clarity):
entr = [
[int(x) for x in input().split()]
for i in range(int(input()))
]
You have that same nested comprehension except that the inner one has been written as a generator passed to the list constructor so it looks like list(int(x) for x in input().split()) instead of [int(x) for x in input().split()]. That's a little more confusing than using a list comprehension.
I hope that explanation helps!

Index out of range - Python

I was programming at CodeWars using Kata, when i got this error:
Traceback:
in
in title_case
IndexError: list index out of range
Here is my code:
def title_case(title, minor_words=1):
string = title.split()
outList = []
if minor_words != 1:
split = minor_words.split()
minor = [x.lower() for x in split]
out = ""
for i in range(0, len(string)):
word = ""
for j in range(0,len(string[i])):
elem = ""
elem += string[i][j]
if j == 0:
word += elem.upper()
else:
word += elem.lower()
if i != len(string)-1:
outList.append(word+" ")
else:
outList.append(word)
list = [x.lower() for x in outList]
print ((list[0]))#Just for debug
if minor_words != 1:
for i in range(0, len(outList)):
if (list[i] in minor):
print("OI")#Just for debug
out += list[i]
else:
out += outList[i]
return out
Well, this happened when trying to execute the code, of course!
One way to initialize this function would be:
title_case('a clash of KINGS', 'a an the of')
Well the 0 elemeny exists, but it says it doesn't, I don't know why, because when I write "print(list)" it shows me the elements of list, in this case, "['a', 'clash', 'of', 'kings']".
What can I do?
Okay, so based on reading this code I think the result you desire from:
title_case('a clash of KINGS', 'a an the of') is:
A Clash of Kings
So it looks like you are stepping through a lot of hoops trying to get there. While I was going through the code it took me a while to see what was actually happening. I also took the liberty to make your variables more consistently named. Rather than mixing caseLetter and case_letter randomly I made it consistent. I also made your loops easier to read. Also for the minorWords argument. Might as well have it passed as a list rather than converting it to a list inside the function. Anyway, I hope this is of help.
def titleCase(title, minorWords=[]):
titleList = [x.lower() for x in title.split()]
outList = []
for Word in titleList:
if Word not in minorWords:
Word = Word.capitalize()
outList.append(Word)
return " ".join(outList)
TitleCased = titleCase("a clash of KINGS", ["an", "the", "of"])
print (TitleCased)
Which outputs A Clash of Kings, which I believe, based on your question and how I understood your code is what you wanted to achieve? Or if you include a in your minorWords, it would be:
a Clash of Kings
Regardless, hope this answers your question!

Create a list from many other lists f#

First of all im VERY VERY noob in f# so I need your help :)
I have a library with 50 lists that each have around 10 entries
What I need to do is join all 50 lists into one big list. The things is that I cant use "for" or mutable variables.
what I have done (which I think is horribly done) is:
let rec finalList x =
if x < wallID.Length then List.append [interfaz.hola(wallID.Item(x)).[0].[1]] [finalList]
else listaFinal (x+1)
printfn "list %A" (listaFinal 10 )
WallID represents one of the 50 lists and interfaz.GetMuroHumano(wallID.Item(x)).[0].[1] gets me one of the entries that I need. (for now if a can just get one of the data for each wallID im ok)
again im verrrrry noob and I hope you guys can help me
thanks
EDIT:
So now its partially working..
let rec finalList x y =
if x < wallID.Length then
if y < [interfaz.GetMuroHumano(wallID.Item(x)).[y]].Length then
let current = [interfaz.GetMuroHumano(wallID.Item(x)).[y].[1]]
let rest = finalList (x y+1)
List.append current rest
else finalList (x+1 y)
else []
vut im getting errors calling the function finalList it says that "y" is not an int but a string
It is hard to say what is wrong with your code without seeing a complete version. As Daniel points out, there is a built-in library function for doing that - in fact, you do not even need List.collect, because there is List.concat that takes a list of lists.
However, you might still try to get your original code to work - this is useful for understanding functional concepts! I added some comments that can help you understand how it should work:
let rec finalList x =
if x < wallIDLength then
// Get the list at the index 'x'
let current = interfaz.GetMuroHumano(wallID.Item(x))
// Recursively process the rest of the lists
let rest = finalList (x + 1)
// Check that both 'current' and 'rest' are variables
// of type list<'T> where 'T is the element type
List.append current rest
else
// Return empty list if we got too far
[]
// Start from the first index: 0
printfn "list %A" (finalList 0)
let flatten xs = List.collect id xs

Resources