Python how to count the nested list of lists containing strings
Question:
I have a nested lists of list. I want to know total items in the main and sublists. Then accordingly I want to choose a value for each sublist or item.
My code:
y = ['ab',['bc','cd'],'ef']
print([len(y[i]) for i in range(len(y))])
alpha=0.5
plot_alpha = [alpha for i in range(len(y)) if len(y[i])>1 else 0.5]
print(plot_alpha)
My present answer:
[2, 2, 2]
[0.5, 0.5, 0.5]
Expected answer:
[1, 2, 1]
[1, 0.5, 1]
Answers:
You can check if each element is a list and handle them differently.
print([len(x) if isinstance(x, list) else 1 for x in y])
# [1, 2, 1]
plot_alpha = [alpha if isinstance(x, list) else 1 for x in y]
# [1, 0.5, 1]
I have a nested lists of list. I want to know total items in the main and sublists. Then accordingly I want to choose a value for each sublist or item.
My code:
y = ['ab',['bc','cd'],'ef']
print([len(y[i]) for i in range(len(y))])
alpha=0.5
plot_alpha = [alpha for i in range(len(y)) if len(y[i])>1 else 0.5]
print(plot_alpha)
My present answer:
[2, 2, 2]
[0.5, 0.5, 0.5]
Expected answer:
[1, 2, 1]
[1, 0.5, 1]
You can check if each element is a list and handle them differently.
print([len(x) if isinstance(x, list) else 1 for x in y])
# [1, 2, 1]
plot_alpha = [alpha if isinstance(x, list) else 1 for x in y]
# [1, 0.5, 1]