Removing tuple from nested list with tuple and lists - list

I have a nested output in the form of this:
[(3, [['Avg_Order_Insert_Size', '572.9964086553654'], ['Avg_Order_Insert_Size', '34.858670832934195'],
['Avg_Order_Insert_Size', '22.09531308137768']])]
And I want to get rid of the int (3) which is in a tuple, and save the lists containing strings and ints.
How do I accomplish this in the best way?
My goal is to use the lists within the tuple for creating a dictionary later on, but while these ints are there within the tuple I don't know what to do. Basically I think I want an output such as:
[([['Avg_Order_Insert_Size', '572.9964086553654'], ['Avg_Order_Insert_Size', '34.858670832934195'],
['Avg_Order_Insert_Size', '22.09531308137768']])]

I think this is enough:
>>> value = [(3, [['Avg_Order_Insert_Size', ...
>>> value[0] = value[0][1:]
>>> value
[([['Avg_Order_Insert_Size', '572.9964086553654'], ['Avg_Order_Insert_Size', '34.858670832934195'], ['Avg_Order_Insert_Size', '22.09531308137768']],)]

Related

How to show which values of one list are in other list?

Having 2 lists, I want check which values of List1 are in List2. I'm trying as below but I get error
List1 = {3,2,8,7,5}
List2 = {1,3,4,2,6,7,9}
= List.Transform(List1, each Text.Contains(List2, _))
Expression.Error: We cannot convert a value of type List to type Text.
Details:
Value=[List]
Type=[Type]
My expected output would be 3,2,7.
How can I do this?
See List.Intersect Documentation
Intersect = List.Intersect({List1,List2})
#horseyride has probably the best answer but using your original logic, you could also write the intersection like this:
List.Select(List1, each List.Contains(List2, _))
This uses Select instead of Transform since you are trying to select/filter instead of changing the elements and uses the appropriate List type instead of Text for the Contains part.

Select duplicated lists from a list of lists (Python 2.7.13)

I have two lists, one is a list of lists, and they have the same number of indexes(the half number of values), like this:
list1=[['47', '43'], ['299', '295'], ['47', '43'], etc.]
list2=[[9.649, 9.612, 9.42, etc.]
I want to detect the repeated pair of values in the same list(and delete it), and sum the values with the same indexes in the second list, creating an output like this:
list1=[['47', '43'], ['299', '295'], etc.]
list2=[[19.069, 9.612, etc.]
The main problem is that the order of the values is important and I'm really stuck.
You could create a collections.defaultdict to sum values together, with keys as the sublists (converted as tuple to be hashable)
list1=[['47', '43'], ['299', '295'], ['47', '43']]
list2=[9.649, 9.612, 9.42]
import collections
c = collections.defaultdict(float)
for l,v in zip(list1,list2):
c[tuple(l)] += v
print(c)
Alternative using collections.Counter and which does the same:
c = collections.Counter((tuple(k),v) for k,v in zip(list1,list2))
At this point, we have the related data:
defaultdict(<class 'float'>, {('299', '295'): 9.612, ('47', '43'): 19.069})
now if needed (not sure, since the dictionary holds the data very well) we can rebuild the lists, keeping the (relative) order between them (but not their original order, that shouldn't be a problem since they're still linked):
list1=[]
list2=[]
for k,v in c.items():
list1.append(list(k))
list2.append(v)
print(list1,list2)
result:
[['299', '295'], ['47', '43']]
[9.612, 19.069]

How to add sequential numbers to a list of tuples

I have a question which looks quite simple, but I could not find an acceptable answer as yet. It looks that variations of it have already been asked here several times, but none of the answers was helpful to me.
Here it is:
I have a lists of tuples, as follows:
reflist = [("Author1", 1900, "Some reference"), ("Author2", 1901, "Another reference"), ("Author3", 1902, "Yet another reference")]
What I want is to add a sequential number to each tuple in the list, so that I got:
reflist = [(1, "Author1", 1900, "Some reference"), (2, "Author2", 1901, "Another reference"), (3, "Author3", 1902, "Yet another reference")]
This looks silly and a list comprehension should do the trick, but I cannot discern just how :-(
Thanks in advance for any assistance you can provide.
enumerate() runs over a sequence and generates index, value pairs. You can't merge directly into your tuples - because tuples are immutable, you can't change their length - but one way you could do it is to convert the tuples you have into lists, make the index number a list, concatenate the two lists together, and convert the result to a tuple:
reflist2 = [tuple([index+1] + list(ref)) for index, ref in enumerate(reflist)]
(I've edited it to index+1 because enumerate starts counting from 0)
f = [tuple(list(elem).insert(0, i)) for elem in reflist for in range(len(reflist))]
What this list comprehension does is that it tells for each original entry in reflist, it should convert it to a list, then insert a number in some integer list to the 0 position of the list, then convert that list back into a tuple, and put it all together in a ne wlist.

Intersection of a set and list of dictionaries

I have a set my_set = ("a","b","c","d","z") and a list my_list=[{"a",0.5},{"c",0.6},{"b",0.9},{"z",0.5},{"m",0.0}]. I would like to have a list with items containing keys in my_set only. In this case the result I would like to have is new_list=[{"a",0.5},{"c",0.6},{"b",0.9},{"z",0.5}]
The list and set is large. Is there an efficient way to accomplish this?
Assuming that that's actually a set and a list of dicts, as stated in the question, you can try this:
In [1]: my_set = set(["a","b","c","d","z"])
In [2]: my_list=[{"a":0.5},{"c":0.6},{"b":0.9},{"z":0.5},{"m":0.0}]
In [3]: [d for d in my_list if all(k in my_set for k in d)]
Out[3]: [{'a': 0.5}, {'c': 0.6}, {'b': 0.9}, {'z': 0.5}]
This simply uses a list comprehension to check that all the keys in the dicts are contained in the set. This will have complexity of O(nm), for n dicts in the list, with m keys each (m being 1 in your case) and assuming that set-lookup is always O(1).
Note, however, that you do not really need a list of dictionaries, since all the keys seem to be different (in this example, at least), so a single dictionary would be enough.

If the set.add() function and list serve for the same purpose in Python?

As what mentioned in the Title, if both of them serve for the same purpose?
Most of the time i will chose to use list, and i don't know when is a better time to use set.add() function.
I try both of them and give me the exact same result...
Personally feel list is better. What do you guys think?
a = set()
a.add('a1')
a.add('a2')
a.add('a3')
for ele in a:
print ele
b = []
b.append('a1')
b.append('a2')
b.append('a3')
for ele in b:
print ele
Please advise...
In terms of general data structures, a set structure tends to allow only one element of each value whereas a list may have more than one of each.
In other words, the pseudo-code set.add(7) executed twice results in the set containing the single element 7 (or an error if it considers adding the same element twice to be invalid).
Using a list instead of a set would result in two elements, both being 7.
For Python specifically, adding duplicates to a set is not an error but it still plainly only allows one of each:
>>> s = set()
>>> s.add(1)
>>> s.add(1)
>>> s.add(2)
>>> s
set([1, 2])
The list on the other hand allows multiples:
>>> l = list()
>>> l.append(1)
>>> l.append(1)
>>> l.append(2)
>>> l
[1, 1, 2]
The reason why you didn't see a difference is simply because you added three unique items to the list and set. In that context, they act the same. Behaviour only diverges when you add duplicate items.