Removes braces from variable - django

I am comparing two list:
gp_yu = set(agencys_sp2).intersection(gp_list_t)
the output is in braces like this {900}. What can i do to remove the braces

You can obtain an element from an iterable iterable (a set is an iterable, but lists, dictionaries, etc. are iterables as well) with:
element = next(iter(iterable))
In case the iterable contains two or more elements, it will return the first element (a set has no really a "first" element in the sense that the order can very over time, but it will return an element).
In case the iterable contains no elements at all (an empty set, list, tuple, dictionary, etc.), then it will raise a StopIteration error. You can however let the expression return a default value with:
element = next(iter(iterable), default)
So in case iterable contains one or more elements, the "first" element is returned, in case it is empty, it will return default.

Probably you mean some like how to get your set as a string, so just use join function.
Some like this ', '.join(gp_yu).
Check this topic for more information:
Python: how to join entries in a set into one string?

Related

Scala List of tuple becomes empty after for loop

I have a Scala list of tuples, "params", which are of size 28. I want to loop through and print each element of the list, however, nothing is printed out. After finishing the for loop, I checked the size of the list, which now becomes 0.
I am new to scala and I could not figure this out after a long time googling.
val primes = List(11, 13, 17, 19, 2, 3, 5, 7)
val params = primes.combinations(2)
println(params.size)
for (param <- params) {
print(param(0), param(1))
}
println(params.size)
combinations methods in List create an Iterator. Once the Iterator is consumed using methods like size, it will be empty.
From the docs
one should never use an iterator after calling a method on it.
If you comment out println(params.size), you can see that for loop is printing out the elements, but the last println(params.size) will remain as 0.
Complementing Johny's great answer:
Do you know how I can save the result from combination methods to use for later?
Well, as already suggested you can just toList
However, note there is a reason why combinations returns an Iterator and it is because the data can be too big, if you are okay with that then go ahead; but you may still take advantage of laziness.
For example, let's convert the inner lists into a tuples before collecting the results:
val params =
primes
.combinations(2)
.collect {
case a :: b :: Nil => (a, b)
}.toList
In the same way, you may add extra steps in the chain like another map or a filter before doing the toList
Even better, if your end action is something like foreach(foo) then you do not even need to collect everything into a List
primes.combinations(2) returns Iterator.
Iterators are data structures that allow to iterate over a sequence of
elements. They have a hasNext method for checking if there is a next
element available, and a next method which returns the next element
and discards it from the iterator.
So, it is like pointer to Iterable collection. Once you have done iteration you no longer will be able to iterate again.
When println(params.size) executed that time iteration completed while computing size and now params is pointing to end. Because of this for (param <- params) will be equivalent looping around empty collection.
There can 2 possible solution:
Don't check the size before for loop.
Convert iterator to Iterable e.g. list.
params = primes.combinations(2).toList
To learn more about Iterator and Iterable refer What is the relation between Iterable and Iterator?

How do I output a specific item in a list when inputted a number that corresponds to that item? [Indexing?]

Number,IceCream
1,Chocolate
2,Vanilla
3,Mixed
Say if I
Number = input("Flavor?:")
I know that I need to index [0] because the numbers are on the first column. I also know that I will need to use .split(",") to remove the commas and to create a list.
Some assistance would be greatly appreciated!
It's confusing whether you plan to include integers in the list with the strings or not
Method 1: including integers with strings(flavor), create a list of tuples
icecream=[(1,'choc'),(2,'mix'),(3,'blueberry')]
print(icecream[0][1])
print(icecream[2][1])
Note: tuples are immutable
Method 2: I believe the best way to do this would be to use a dictionary instead of list. As dictionary has (Key, value) pairs, you could assign key(integer) to values(flavor), which then would make it easy accessing items just by keys(integers in your case) ex.
Ice_cream_flavors={1:"chocolate", 2:"vanilla", 3:"mixed"} #dictionary
to access values, you could use methods available in dictionary use get(), items()
Note: items() returns a tuple for each key,value pair.
ex.
Ice_cream_flavors={1:"chocolate", 2:"vanilla", 3:"mixed"}
new=Ice_cream_flavors.items()
for k,v in new:
if input==k:
print(v)

To append an element into a list without generating any other elements

Trying to append an element into an empty list as follows, while appending it also adds a character 'u' like [u'slice'] into the empty list while adding an element into the list, however expected is ['slice']
Code as follows:
type = slice # value for type
value = []
value.append(type)
Output:
value = [u'slice']
Requesting people for help to get output as ['slice'].
For some reason the output is in Unicode, hence the u. Try re-encoding it to ascii
by using .encode("ascii"). Sorry I don't know why it's doing that though.

difference between [] and list() in python3

I thought that [] and list() were two equal ways to create a list. But if you want a list with dictionnary keys,
var = [a_dict.keys()]
doesn't work since type(var) is [dict_keys], correct syntax is :
var = list(a_dict.keys())
I couldn't find an good explanation on this behaviour. Do you have one ?
TL;DR:
list() is the same as []
list(obj) is not the same as [obj]
a_dict.keys() is a dictionary view object, it returns an object which can be iterated to yield the keys of a_dict. So this line:
[a_dict.keys()]
is saying in python "I'm making a list with one element in it" and that one element is the dict keys iterator. It's a list literal in the syntax.
Now this line:
list(a_dict.keys())
is a call to the list builtin function. This function list attempts to iterate the argument and produce a list. It's a function call in the grammar.
The equivalent list literal (actually list comprehension) would be instead:
[key for key in a_dict.keys()]
Finally, note that dictionary objects iterate by keys anyway,
list(a_dict.keys()) would usually be written more simply as as list(a_dict) instead.
Hope this helps.
[a_dict.keys()]
This one puts a single element in the list. Just as if you were to write [1]. In this case that one element is going to be a list.
list(a_dict.keys())
The constructor accepts a sequence and will add all elements of the sequence to the container.

Nil vs List(Nil) in a for with recursion

I'm learning Scala and have a quick question: Can someone please explain to me why the following two sets of code yield different results?
def grey0(n: Int): List[List[String]]={
if (n==0) List(Nil)
else for(i<-List("0","1"); j<-grey0(n-1)) yield i :: j
}
versus
def grey1(n: Int): List[List[String]]={
if (n==0) Nil
else for(i<-List("0","1"); j<-grey0(n-1)) yield i :: j
}
The first option yields the result I am looking for. What I don't understand is, why does the second option just return the empty list? I would have thought the other results would cons on to it and if anything, I would get some sort of flat list rather than a List[List[String]] (which is what I want).
In your first version grey0(0) will return a 1-element list that contains the empty list. grey0(1) will, for each element in grey0(0) create two lists, so you get a total of two lists because grey0(0) contains one list. Likewise grey0(2) will contain 4 lists because for each of the two elements in grey0(1) it creates 2 lists.
In your second version grey0(0) will return the empty list. grey0(1) will create two lists for each element in grey0(0). Since grey0(0) has 0 elements, that makes a total of 0*2=0 elements in the result.
In the first example, you create a list containing an empty list. In the second example you create just an empty list. Both can have the same type, because any list can be empty.
Nil just means empty list and it is almost equal to List() (in your example types will be inferred so both are exactly the same). List(Nil) is then like List(List()).