Need to generate a dictionary using comprehension - python-3.x

I have this code in python:
layers = ['two', 'three', 'five', 'six']
dict_toggle_bullet = {}
for x, y in enumerate(layers):
dict_toggle_bullet[y] = ["active" if j == y else "" for _, j in enumerate(layers)]
The output is:
{'two': ['active', '', '', ''], 'three': ['', 'active', '', ''], 'five': ['', '', 'active', ''], 'six': ['', '', '', 'active']}
Is there a way to convert this using dictionary comprehension in a single line?

This is what I came up with:
lst = ['two','three','five','six']
d = {lst[i]:['' if j != i else 'active' for j in range(4)] for i in range(4)}
However, I wouldn't advice you to do this as it seems a bit complicated and difficult to understand, so the direct method looks to be better.

Related

Converting matrix of strings to PyTorch tensor

I wanted to convert the following matrix into a PyTorch tensor:
[['SELF', '', '', '', ''],
['nsubj', 'SELF', '', '', ''],
['', 'compound', 'SELF', '', ''],
['dobj', '', '', 'SELF', ''],
['pobj', '', '', '', 'SELF']]
I wanted to have a boolean matrix where any position with a string other than empty would have a 1, otherwise 0. This should be easy, but I do not seem to find an answer that does not require to iterate through the matrix and build the tensor a cell at a time.
The solution I have:
size = len(sample["edges"])
edge_mask = torch.zeros([size, size])
for i, row in enumerate(sample["edges"]):
for j, v in enumerate(row):
if v != "":
edge_mask[i, j] = 1
You can convert it to a boolean array, then use torch.from_numpy followed with a convert to int:
torch.from_numpy(np.array(sample["edges"], dtype=bool)).to(int)

Removing empty strings in a list

I have a list in the form
lst = ['', 'how', '', 'are', 'you', '']
and want to convert it into
lst = ['how','are', 'you']
I have currently used the code list(filter(None,lst)) but no changes are returned. How can i remove the empty strings?
Your code must works but an other solution is using lambdas:
lst = list(filter(lambda x: x != '', lst))
print(lst)
Output: ['how', 'are', 'you']
A simple and possible solution is the following:
lst = ['', 'how', '', 'are', 'you', '']
lst = [element for element in lst if element != '']
Now, lst is ['how', 'are', 'you']
Here you forgot to make the filter to this kinda thing:
lst = ['', 'how', '', 'are', 'you', '']
lst = list(filter(None, lst))
print(lst)
you define the list as list(filter(None, lst))
Are you printing lst again? Your code works for me.
lst = ['', 'how', '', 'are', 'you', '']
lst = list(filter(None,lst))
print(lst)
outputs ['how', 'are', 'you']

text file with list of list to open as dataframe

I am new to python. I have a text file as 'asv.txt' having the following content:
[['10', '50', '', ' Ind ', '', ''], ['40', '30', '', ' Ind ', 'Mum', ''], ['50', '10', '', ' Cd ', '', '']]
How do I read it as a csv or as a dataframe.
# Read file (or just copy text)
with open('asv.txt') as f:
data = f.read()
# Convert str to list with ast
import ast
data = ast.literal_eval(data)
## Load dataframe using the "data" argument, which can accept a list and treats it as rows
df = pd.DataFrame(data=data)
Or much simpler for this specific case:
df = pd.DataFrame(data=[['10', '50', '', ' Ind ', '', ''], ['40', '30', '', ' Ind ', 'Mum', ''], ['50', '10', '', ' Cd ', '', '']])

Convert given list to nested list - Python3.x

I have a list in the below format :
input = [['Monday', 'Tuesday', 'Wednesday', '', '1', '2', 'Black', '']]
I would like to convert this to a nested list like below : (See, nested list breaks at null element)
output = [['Monday', 'Tuesday', 'Wednesday'], ['1', '2', 'Black']]
Is there a way to do this? I tried hard to think but could not come up with a solution.
More Examples :
input = [['', 'word1', 'word2', '', '1', '2', 'orange', '']]
output = [['word1', 'word2'],['1', '2', 'orange']]
input = [['', '', 'word1', 'word2', '', '1', '2', 'word3', '', '']]
output = [['word1', 'word2'],['1', '2', 'word3']]
Thanks in advance!!!
That should work:
import itertools
input_ = [['Monday', 'Tuesday', 'Wednesday', '', '1', '2', 'Black', '']]
output = [list(g) for item in input_ for k, g in itertools.groupby(item, bool) if k]
Longer solution:
input_ = [['Monday', 'Tuesday', 'Wednesday', '', '1', '2', 'Black', '']]
output = []
sublist = []
for item in input_:
for subitem in item:
if subitem:
sublist.append(subitem)
continue
if sublist:
output.append(sublist)
sublist = []
Here is a way to do it:
x = [['', '', 'word1', 'word2', '', '1', '2', 'word3', '', '']]
output = []
temp = []
for idx, el in enumerate(x[0]):
if idx == 0 and el == "":
continue
if el != '':
temp.append(el)
elif temp != []:
output.append(temp)
temp = []
Output
[['word1', 'word2'], ['1', '2', 'word3']]

What does the following code say in the simple way?

Can you tell me what this code says in the simple way:
board = [['' for x in range(BOARD_SIZE)] for y in range(BOARD_SIZE)]
This code creates a list of BOARD_SIZE lists. Each of these lists will contain BOARD_SIZE empty strings. So if BOARD_SIZE is 3 then the board will be:
board = [ ['', '', ''],
['', '', ''],
['', '', ''] ]
You can rewrite this code in a single line:
board = [['', '', ''], ['', '', ''], ['', '', '']]

Resources