I have a nested list as follows:
[[u'56', u'99', u'160'], [u'74', u'113', u'169'], [u'92', u'127', u'177'], [u'110', u'142', u'186'], [u'128', u'156', u'195'], [u'146', u'170', u'203'], [u'165', u'184', u'212'], [u'183', u'198', u'220'], [u'201', u'212', u'229'], [u'219', u'227', u'238'], [u'237', u'241', u'246']]
I want to pass each list as a sequence to the following map function:
map(None, nested_list1, nested_list2 ...]
So that, I get 3 lists, where, the first list contains the first element from all the nested_lists, the second list contains the second element from all the nested_lists.
So far, after many tries, I have come up with the following code (it does not involve map()).
first_list = [each[0] for each in nested_list]
second_list = [each[1] for each in nested_list]
third_list = [each[1] for each in nested_list]
I think this can be made into a one-liner if map() is used. Any ideas?
What you want is zip but you can do it with map, you just have to use *list_of_lists to transpose:
a, b, c = map(None,*l)
If you want list you would have to also map to list:
map(None,*l)
Really you should use zip:
a,b,c = map(list,zip(*l))
Both will give the same output in python 2:
In [19]: a,b,c = map(list,map(None,*l))
In [20]: print a
[u'56', u'74', u'92', u'110', u'128', u'146', u'165', u'183', u'201', u'219', u'237']
In [21]: print b
[u'99', u'113', u'127', u'142', u'156', u'170', u'184', u'198', u'212', u'227', u'241']
In [22]: print c
[u'160', u'169', u'177', u'186', u'195', u'203', u'212', u'220', u'229', u'238', u'246']
In [23]: a,b,c = map(list, zip(*l))
In [24]: print a
[u'56', u'74', u'92', u'110', u'128', u'146', u'165', u'183', u'201', u'219', u'237']
In [25]: print b
[u'99', u'113', u'127', u'142', u'156', u'170', u'184', u'198', u'212', u'227', u'241']
In [26]: print c
[u'160', u'169', u'177', u'186', u'195', u'203', u'212', u'220', u'229', u'238', u'246']
But the map approach won't work using python3.
Related
I want to print all elements in this list in reversed order and every element in this list must be on a new line.
For example if the list is ['i', 'am', 'programming', 'with', 'python'] it should print out:
python
with
programming
am
i
What is the best way to do this?
def list():
words = []
while True:
output = input("Type a word: ")
if output == "stop":
break
else:
words.append(output)
for elements in words:
print(elements)
list()
generic :
for(i=wordsArry.size();i--;i<0){
pritnln(wordsArry[i]+"/n")
}
Start iteration from the end of the list - last element in it.
Then iterate backwards - decrease iterator by 1 till you reach 0.
Print each element plus new line symbol - might depend on OS,
language.
In Python you can reverse a list in place by:
words = ['i', 'am', 'programming', 'with', 'python']
words.reverse()
for w in words:
print(w)
If you want to iterate in reverse but keep the original order, you can use a slice:
for w in words[::-1]:
print(w)
Slice syntax is [begin:end:step], where begin (incl) and end (excl) indices are omitted (get all elements) and the step -1 returns a slice with the elements in reverse order.
Both methods produce the same output.
I've below lists,
lists=[ ['arya','egg','milk','butter','bread'],
['Jon','butter','pastrie','yogurt','beer'],
['bran','beer','milk','banana','apples'],]
Each list has values in which the first value is the name of a person and rest of all are some food items. I've a task where I've to create a dictionary with these food items as keys and the person as a value as shown below
dict = { 'egg' : set(['arya']),
'milk': set(['arya','bran']),
'butter' : set(['arya','jon']),
'bread' : set(['arya']),
'pastrie' : set(['jon']),
'milk' : set(['bran'])
} # few keys omitted
This is what I did and stopped, dont know how to proceed further,
food,person = [],[]
for i in lists:
food.append(i[1:])
person.append(i[0])
I was able to seperate the first value of each list and append it to a list
and same with food.
Dont know how to proceed further.
started learning python, Any input is highly helpful. kindly share one or two lines of explanation to enlighten this newbie !
Thank you so much.
Using dictionary method setdefault is helpful here.
You of course don't nee to set the slices to a variable, but it makes it easier to read.
d = {}
for l in lists:
name = l[0]
items = l[1:]
for item in items:
d.setdefault(item, set()).add(name)
Use a collections.defaultdict:
lists = [['arya', 'egg', 'milk', 'butter', 'bread'],
['Jon', 'butter', 'pastrie', 'yogurt', 'beer'],
['bran', 'beer', 'milk', 'banana', 'apples']]
from collections import defaultdict
d = defaultdict(set)
for sub in lists:
for v in sub[1:]:
d[v].add(sub[0])
print(d)
Output:
defaultdict(<class 'set'>,
{'bread': {'arya'}, 'yogurt': {'Jon'}, 'beer': {'Jon', 'bran'},
'banana': {'bran'}, 'butter': {'Jon', 'arya'}, 'milk': {'arya',
'bran'}, 'pastrie': {'Jon'}, 'egg': {'arya'}, 'apples': {'bran'}})
For python3 the syntax is a little nicer:
from collections import defaultdict
d = defaultdict(set)
for name, *rest in lists:
for v in rest:
d[v].add(name)
1.Three lists a, b and c. If a[index] is in b[index] then get the element in list c corresponding to list b[index]. That is if a[0]=b[1],get c[1]:
a = ['ASAP','WTHK']
b = ['ABCD','ASAP','EFGH','HIJK']
c = ['1','2','3','4','5']
I hope this is what you were looking for. You can add the b and the corresponding c value to the dictionary in a loop if the a array contains the b value. After that you can get the c value by a value as key like in the code below.
a = ['ASAP','WTHK']
# b c
dictionary_trans = {'ASAP' : '1'}
dictionary_trans = {'WTHK' : '1337'}
# etc. put all b values existing in a to the dict
# with thier coresponding c values.
key = a[0]
c_value = dictionary_trans.get(key)
print c_value
My python skills are very limited, but I think I would try to solve the problem this way.
This solution could crash if you use an a value which is not contained in the dictionary, so you need to implement some logic to handle missing relations between a and c, like insert dummy entries to the dictionary or so.
I have a couple List<string>s, with the format like this:
List 1 List 2 List 3
1 A One
2 B Two
3 C Three
4 D Four
5 E Five
So in code form, it's like:
List<string> list1 = {"1","2","3","4","5"};
List<string> list2 = {"A","B","C","D","E"};
List<string> list3 = {"One","Two","Three","Four","Five"};
My questions are:
How do I transfom those three lists to a CSV format?
list1,list2,list3
1,A,one
2,b,two
3,c,three
4,d,four
5,e,five
Should I append , to the end of each index or make the delimeter its own index within the multidimensional list?
If performance is your main concern, I would use an existing csv library for your language, as it's probably been pretty well optimized.
If that's too much overhead, and you just want a simple function, I use the same concept in some of my code. I use the join/implode function of a language to create a list of comma separated strings, then join that list with \n.
I'm used to doing this in a dynamic language, but you can see the concept in the following pseudocode example:
header = {"List1", "List2", "List3"}
list1 = {"1","2","3","4","5"};
list2 = {"A","B","C","D","E"};
list3 = {"One","Two","Three","Four","Five"};
values = {header, list1, list2, list3};
for index in values
values[index] = values[index].join(",");
values = values.join("\n");
I have a list like df_all (see below).
A = matrix( ceiling(10*runif(8)), nrow=4)
colnames(A) = c("country", "year_var")
dfa = data.frame(A)
df1 = dfa[1,]
df2 = dfa[2,]
df3 = dfa[3,]
df4 = dfa[4,]
df_all = list(df1, df2, df3, df4)
df_all
Now I want to combine the list of interest by using variable a.
a <- "2,3,4"
b <- strsplit(a, ",")[[1]]
To combine this lists, I use the folling loop:
for (i in 1:length(b)){
c<-b[i]
aa <- df_all[c:c]
print(aa)
}
Now my question is, How can I combine this result and save this as as variable?
Thanks!
Would this work for you:
basnum<-as.integer(b)
do.call(rbind, df_all[basnum])
Through df_all[basnum], a list with only the relevant data.frames is created.
do.call takes a function and a list as parameters (and some more but not relevant right now). The items of the list are then passed on as parameters to the function.
So in this case, the above is the equivalent to calling:
rbind(df_all[[2]], df_all[[3]], df_all[[4]])
And this produces one data.frame holding all the rows of interest.