Python check variable against multiple lists - python-3.x

So I have 3 lists of data, I need to test if any of the data I get from the json response is in any of the lists, I'm probably being stupid about it but I'm trying to learn and can't seem to get it to work right.
list1 = ['a', 'b', 'c']
list2 = ['a1', 'b1', 'c1']
list2 = ['a2', 'b2', 'c2']
#block of code...
#block of code...
content = json.loads(response.read().decode('utf8'))
data = content
for x in data:
#if x['name'] in list1: #This works fine the line below does not.
if x['name'] in (list1, list2, list3):
print("something")

I suggest something simple and straight-forward:
if (x['name'] in list1 or
x['name'] in list2 or
x['name'] in list3):
...

As a pythinc way for such tasks you can use any for simulating the OR operand and all for and operand.
So her you can use a generator expression within any() :
if any(x['name'] in i for i in (list1, list2, list3))

What about concatenating the lists?
if x['name'] in [list1 + list2 + list3]:

Related

How to get unique values in nested list along single column?

I need to extract only unique sublists based on first element from a nested list. For e.g.
in = [['a','b'], ['a','d'], ['e','f'], ['g','h'], ['e','i']]
out = [['a','b'], ['e','f'], ['g','h']]
My method is two break list into two lists and check for elements individually.
lis = [['a','b'], ['a','d'], ['e','f'], ['g','h']]
lisa = []
lisb = []
for i in lis:
if i[0] not in lisa:
lisa.append(i[0])
lisb.append(i[1])
out = []
for i in range(len(lisa)):
temp = [lisa[i],lisb[i]]
out.append(temp)
This is an expensive operation when dealing with list with 10,00,000+ sublists. Is there a better method?
Use memory-efficient generator function with an auziliary set object to filter items on the first unique subelement (take first unique):
def gen_take_first(s):
seen = set()
for sub_l in s:
if sub_l[0] not in seen:
seen.add(sub_l[0])
yield sub_l
inp = [['a','b'], ['a','d'], ['e','f'], ['g','h'], ['e','i']]
out = list(gen_take_first(inp))
print(out)
[['a', 'b'], ['e', 'f'], ['g', 'h']]

Why does not ''.join(list1) work after insert a new element?

I have a list list = ['a', 'b']. Then I create a new list by list1 = list.insert(0, 'c'). After that I want to join all the strings in list1 by ''.join(list1). Could you please explain why how to resolve the error can only join an iterable?
list = ['a', 'b']
list1 = list.insert(0, 'c')
''.join(list1)
list.insert(0, 'c') does not return anything, so to do this you can write
list = ['a', 'b']
list.insert(0, 'c')
print(''.join(list))
Output: 'cab'

Define function that reads from Lists of lists

Heres a quick example:-
setup = [['dog','red','big','ears'],
['cat','blue','small','tail']]
def do_it(dummy_parameter):
if do_it [0][0] == 'dog':
print 'dog'
elif do_it [0][0] == 'cat'
print 'cat'
do_it(setup)
Basically looking to go through a list of up to four lists, make an action depending on each of the list contents.. It a bit vague but any assistance would be appreciated! :)
Getting the error
TypeError: 'function' object has no attribute '__getitem__'
Here is an example how to get all the values from a list and list of list :)
with recursion :)
test = [['a', 'b', 'c'],['d', 'e'], 'f']
def separate(item):
try:
for i in item:
if type(i) == list:
separate(i)
else:
print(i)
except IndexError:
pass
separate(test)

convert a list of lists to a list of string

I have a list of lists like this
list1 = [['I am a student'], ['I come from China'], ['I study computer science']]
len(list1) = 3
Now I would like to convert it into a list of string like this
list2 = ['I', 'am', 'a', 'student','I', 'come', 'from', 'China', 'I','study','computer','science']
len(list2) = 12
I am aware that I could conversion in this way
new_list = [','.join(x) for x in list1]
But it returns
['I,am,a,student','I,come,from,China','I,study,computer,science']
len(new_list) = 3
I also tried this
new_list = [''.join(x for x in list1)]
but it gives the following error
TypeError: sequence item 0: expected str instance, list found
How can I extract each word in the sublist of list1 and convert it into a list of string? I'm using python 3 in windows 7.
Following your edit, I think the most transparent approach is now the one that was adopted by another answer (an answer which has since been deleted, I think). I've added some whitespace to make it easier to understand what's going on:
list1 = [['I am a student'], ['I come from China'], ['I study computer science']]
list2 = [
word
for sublist in list1
for sentence in sublist
for word in sentence.split()
]
print(list2)
Prints:
['I', 'am', 'a', 'student', 'I', 'come', 'from', 'China', 'I', 'study', 'computer', 'science']
Given a list of lists where each sublist contain strings this could be solved using jez's strategy like:
list2 = ' '.join([' '.join(strings) for strings in list1]).split()
Where the list comprehension transforms list1 to a list of strings:
>>> [' '.join(strings) for strings in list1]
['I am a student', 'I come from China', 'I study computer science']
The join will then create a string from the strings and split will create a list split on spaces.
If the sublists only contain single strings, you could simplify the list comprehension:
list2 = ' '.join([l[0] for l in list1]).split()

recursively add to python dictionary from tuple

I'm attempting to take the tuple ('a', 'b', 'c') and create a layered dictionary like this:
{'a': {'b': {'c': {}}}}. I'm using recursion to do this. When I print out the dictionary after each stage of my script (many prints simply for debugging purposes) it shows that the dictionary is being created correctly, but then it is taken apart and left incorrect. The dictionary I'm left with is {'c': {}}. I must be doing something improper with the recursion part. Any help will be much appreciate. Here is my code:
def incr_dict(dct, tpl):
if len(tpl) == 0:
dct = dct
print(dct)
print('1')
else:
dct = {tpl[-1]:dct}
print(dct)
print('2')
incr_dict(dct, tpl[0:-1])
print(dct)
print('3')
return dct
dct = {}
tpl = ('a', 'b', 'c')
dct=incr_dict(dct, tpl)
print(dct)
print('4')
You're ALMOST there!! Change the incr_dict(dct, tpl[0:-1]) line to read return incr_dict(dct, tpl[0:-1]). I believe that will fix the problem.
When using recursion, it is important to return the recursive call -- otherwise the 'higher levels' of the recursion can't make use of the new information. By returning the recursion, the execution will continue to recurse until the terminating condition is met, and then the computed values will begin to be returned up the chain until they are finally returned from the first invocation of the function.
The final code should look as follows:
def incr_dict(dct, tpl):
if len(tpl) == 0:
dct = dct
else:
dct = {tpl[-1]:dct}
return incr_dict(dct, tpl[0:-1])
return dct
dct = {}
tpl = ('a', 'b', 'c')
dct=incr_dict(dct, tpl)
print(dct)
I removed some of the debugging statements for clarity.

Resources