I have a couple of lists with progressively decreasing number of items like below:
list1 = [10 20 30]
list2 = [50 60]
list3 = [80]
I want to print the lists such that the last item of the succeeding lists after the 1st list is flushed-right, i.e, the last items of the lists, e.g. 30 60 80 are aligned under the last column of list1.
Here's a snippet of my list and the codes that I used to display the list as I wanted:
s1 = [4.98, 14.41, -3.16, 2.74. -12.32]
s2 = [-6.59, 14.14, 8.84, 5.68]
s3 = [-29.95, 18.95, 15.75]
s4 = [11.44, -8.22]
s5 = [30.96]
The lists show flushed-left when printed, all first items aligned in col 1. As I mentioned, I want to print it fushed-right, all last items aligned together in the last column of list s1.
I padded the "blanks" of lists whose lengths are less than list s1 with a dummy item ('zzzz') to see if I could print flushed-right.
Pad1 = ['zzzz']
Pad2 = ['zzzz', 'zzzz']
Pad3 = ['zzzz', 'zzzz', 'zzzz']
Pad4 = ['zzzz', 'zzzz', 'zzzz', 'zzzz']
df_join1 = Pad1 + s2
df_join2 = Pad2 + s3
df_join3 = Pad3 + s4
df_join4 = Pad4 + s5
Padding works, got the last item of each list to print flushed right but the outlook is ugly as the numbers in columns are not properly aligned.
There must be a better way to do it. Would greatly appreciate a useful lead. I must admit, my script codes aren't the most efficient. I can clean them up later. For now, I just want to see if there's a better way.
Much thanks.
Related
I have a question about writing for loops in python 3.
Basically, I don't understand how to write for loop if I have a list that contains two elements, like this one:
list1 = [("Berlin", 22), ("Zagreb", 30), ("New York", 25), ("Chicago", 20), ("Paris", 29)]
This is basically a list that contains cities and their temperatures in Celsius degrees, and I would like to create a new list that contains cities but now their temperature in Fahrenheit. The formula is:
F° = (9/5)*C° + 32
I don't understand how am I suppose to loop through this list that contains two elements in every member.
Use a list comprehension:
list1 = [("Berlin", 22), ("Zagreb", 30), ("New York", 25), ("Chicago", 20), ("Paris", 29)]
list2 = [(city, 9/5 * temp + 32) for city, temp in list1]
print(list2)
# [('Berlin', 71.599999999999994), ('Zagreb', 86.0), ('New York', 77.0), ('Chicago', 68.0), ('Paris', 84.200000000000003)]
Here, you iterate through list of tuples getting city names to city and temperature in Celsius to temp and convert Celsius to Farenheit.
Without list comprehension:
list2 = []
for city, temp in list1:
list2.append((city, 9/5 * temp + 32))
print(list2)
# [('Berlin', 71.599999999999994), ('Zagreb', 86.0), ('New York', 77.0), ('Chicago', 68.0), ('Paris', 84.200000000000003)]
First thing you need to know is to access elements in a 2D list. According to your list1, city is in the 0th position and temperature is in 1st position in a row. Within a simple for loop, you can access those as follows. Remember to keep the indentation, to specify the body of the for loop.
for element in list1:
city = element[0]
temp_c = element[1]
Then you can directly use temp_c to compute temperature in Fahrenheit (temp_f), within the loop.
temp_f = (9 / 5) * temp_c + 32
Next task is to append calculated temp_f values to a new list (list2) along with city name.
list2.append((city, temp_f))
But before that you should define the list2. (somewhere near you define list1)
list2 =[]
So it's done. You can check it works using a print statement.
for element in list2:
print(element)
This code can be implemented much shorter.
I expand it to reduce the complexity. Hope you got it.
I have a list like below and need to firs add items in each list and then multiply all results 2+4 = 6 , 3+ (-2)=1, 2+3+2=7, -7+1=-6 then 6*1*7*(-6) = -252 I know how to do it by accessing indexes and it works (as below) but I also need to do it in a way that it will work no matter how many sublist there is
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
a= nested_lst[0][0] + nested_lst[0][1]
b= nested_lst[1][0] + nested_lst[1][1]
c= nested_lst[2][0] + nested_lst[2][1] + nested_lst[2][2]
d= nested_lst[3][0] + nested_lst[3][1]
def sum_then_product(list):
multip= a*b*c*d
return multip
print sum_then_product(nested_lst)
I have tried with for loop which gives me addition but I don't know how to perform here multiplication. I am new to it. Please, help
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]]
for i in nested_lst:
print sum(i)
Is this what you are looking for?
nested_lst = [[2,4], [3,-2],[2,3,2], [-7,1]] # your list
output = 1 # this will generate your eventual output
for sublist in nested_lst:
sublst_out = 0
for x in sublist:
sublst_out += x # your addition of the sublist elements
output *= sublst_out # multiply the sublist-addition with the other sublists
print(output)
This is my code to create lists, but its so brutal and inelegant, you guys have some idea to make it much smoother?
Thing is, I want to write code, where you could create your own lists, choose how many of them you want to create and how much items each should have - NOT using while loop. I can manage creating certain number of lists by inputing the range in for loop (number_of_lists)
i = 0
number_of_lists = input('How many lists you want to make? >')
for cycle in range(number_of_lists): #this was originaly range(3),
item1 = raw_input('1. item > ') #and will only work now pro-
item2 = raw_input('2. item > ') #perly, if n_o_l is exact. 3
item3 = raw_input('3. item > ')
#everything is wrong with this
print "-------------------" #code, i need it much more au-
#tonomous, than it is now.
if i == 0:
list1 = [item1, item2, item3]
if i == 1:
list2 = [item1, item2, item3]
if i == 2:
list3 = [item1, item2, item3]
i += 1
print list1
print list2
print list3
Thing is I also want to avoid all that 'if i == int' thing.
Now it will only create 3 lists, right, because instead of number_of_lists i originally used integer 3 to make 3 lists.
Now you see my problem I hope. I need to create new lists from input and name them if possible, so instead of list1 i can name it DOGS or w/e.
I need it all much more simple and interconnected, I hope you understand my problem and maybe have some smooth solution, thanks :)
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Ok, I think I got it now - this is new version, doing pretty much what i want it to do:
number_of_lists = input('How many lists you want to make? >')
allItems = []
for cycle in range(int(number_of_lists)):
items = []
number_of_items = input('How much items in this list? >')
for i in range(int(number_of_items)):
item = raw_input(str(i+1) + ". item > ")
items.append(item)
allItems.append(items)
print("-------------------")
print allItems
If anyone has idea how to make this more effective and clear, let me know here! :) thanks for help guyz
You can add your lists to another list, that way it's dynamic like you want. Example below:
number_of_lists = input('How many lists you want to make? >')
allItems = []
for cycle in range(int(number_of_lists)):
items = []
for i in range(1, 4):
item = input(str(i) + ".item > ")
items.append(item)
allItems.append(items)
print("-------------------")
for items in allItems:
for item in items:
print(item)
print("-------------")
You'd still need to check if number_of_lists is an int before parsing it into an int. If the user types a letter it will throw an error.
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 Python list like the following:
['IKW', 'IQW', 'IWK', 'IWQ', 'KIW', 'KLW', 'KWI', 'KWL', 'LKW', 'LQW', 'LWK', 'LWQ', 'QIW', 'QLW', 'QWI', 'QWL', 'WIK', 'WIQ', 'WKI', 'WKL', 'WLK', 'WLQ', 'WQI', 'WQL']
If we pick, say the second element IQW, we see that the list has duplicates of this item HOWEVER its not noticeable right away. This is because it is cyclic. I mean the following are equivalent.
IQW, QWI, WIQ
Also it could be backwards which is also a duplicate so I want it removed. So now the list of duplicates are (the reverse of each of one these)
IQW, QWI, WIQ , WQI, IWQ, QIW
So essentially I would like IQW to be the only one left.
Bonus points, if the one that is remaining in the list is sorted alphabetically.
The way I did was to sort the entire list by alphabetical order:
`IQW`, `QWI`, `WIQ` , `WQI`, `IWQ`, `QIW` ->
`IQW`, `IQW`, `IQW`, `IQW`, `IQW` `IQW`
and then remove the duplicates.
However this also removes combinations say i have ABCD and CDAB. These are not the same because the ends only meet once. But my method will sort them to ABCD and ABCD and remove one.
My code:
print cur_list
sortedlist = list()
for i in range(len(cur_list)):
sortedlist.append(''.join(map(str, sorted(cur_list[i]))))
sortedlist = set(sortedlist)
L = ['IKW', 'IQW', 'IWK', 'IWQ', 'KIW', 'KLW', 'KWI', 'KWL', 'LKW', 'LQW', 'LWK', 'LWQ', 'QIW', 'QLW', 'QWI', 'QWL', 'WIK', 'WIQ', 'WKI', 'WKL', 'WLK', 'WLQ', 'WQI', 'WQL']
seen = set()
res = []
for item in L:
c = item.index(min(item))
item = item[c:] + item[:c]
if item not in seen:
seen.add(item)
seen.add(item[0]+item[-1:0:-1])
res.append(item)
print res
output:
['IKW', 'IQW', 'KLW', 'LQW']
Here is the solution I coded: If anyone has a better algo, I will accept that as answer:
mylist = list()
for item in copy_of_cur:
linear_peptide = item+item
mylist = filter(lambda x: len(x) == 3 , subpeptides_linear(linear_peptide))
for subitem in mylist:
if subitem != item:
if subitem in cur_list:
cur_list.remove(subitem)