Python - Print multiple list in one line - list

I have 4 lists with random data and I want to print them as a table
Example (This is not what I want to print)
list1 = [data01,data02,data03]
list2 = [data04,data05,data06]
list3 = [data07,data08,data09]
list4 = [data10,data11,data12]
when i try the following
print ("\n").join(list1)+'*'.join(list2)+'*'.join(list3)+"*".join(list4)
I get
data01data04data07data10
data02data05data08data11
data03data06data09data12
I'm trying to have them like
data01 * data04 * data07 * data10
data02 * data05 * data08 * data11
data03 * data06 * data09 * data12
Python 2.7.12
Thanks!

Related

converting string characters in 2D list in Python 2.7

I create a 2D list, here is what I tried
list = [[] for i in range(2)]
data = 'abcd'
for row in data:
for col in row:
list[:0] = data
I got
['a','b','c','d', 'a','b','c','d','a','b','c','d','a','b','c','d']
But what I want is
['a','b']
['c','d']
Anyone can help?
You can to this without iteration:
data = 'abcd'
r = [list(data[:2]) , list(data[2:])]
print(r)
#[['a', 'b'], ['c', 'd']]
The following should work:
LIST_SIZE = 2
lists = [[] for _ in range(LIST_SIZE)]
data = 'abcd'
for i in range(LIST_SIZE):
for j in range(LIST_SIZE):
letter = data[LIST_SIZE * i + j]
lists[i].append(letter)

keras custom activation to drop under certain conditions

I am trying to drop the values less than 1 and greater than -1 in my custom activation like below.
def ScoreActivationFromSigmoid(x, target_min=1, target_max=9) :
condition = K.tf.logical_and(K.tf.less(x, 1), K.tf.greater(x, -1))
case_true = K.tf.reshape(K.tf.zeros([x.shape[1] * x.shape[2]], tf.float32), shape=(K.tf.shape(x)[0], x.shape[1], x.shape[2]))
case_false = x
changed_x = K.tf.where(condition, case_true, case_false)
activated_x = K.sigmoid(changed_x)
score = activated_x * (target_max - target_min) + target_min
return score
the data type has 3 dimensions: batch_size x sequence_length x number of features.
But I got this error
nvalidArgumentError: Inputs to operation activation_51/Select of type Select must have the same size and shape. Input 0: [1028,300,64] != input 1: [1,300,64]
[[{{node activation_51/Select}} = Select[T=DT_FLOAT, _class=["loc:#training_88/Adam/gradients/activation_51/Select_grad/Select_1"], _device="/job:localhost/replica:0/task:0/device:GPU:0"](activation_51/LogicalAnd, activation_51/Reshape, dense_243/add)]]
[[{{node metrics_92/acc/Mean_1/_9371}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_473_metrics_92/acc/Mean_1", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
I understand what the problem is; custom activation function cannot find the proper batch size of inputs. But I don't know how to control them.
Can anyone fix this or suggest other methods to replace some of the element values in some conditions?
The error message I got when running your code is:
ValueError: Cannot reshape a tensor with 19200 elements to shape
[1028,300,64] (19737600 elements) for 'Reshape_8' (op: 'Reshape') with
input shapes: [19200], [3] and with input tensors computed as partial
shapes: input[1] = [1028,300,64].
And the problem should be that you cannot reshape a tensor of shape [x.shape[1] * x.shape[2]] to (K.tf.shape(x)[0], x.shape[1], x.shape[2]). This is because their element counts are different.
So the solution is just creating a zero array in right shape.
This line:
case_true = K.tf.reshape(K.tf.zeros([x.shape[1] * x.shape[2]], tf.float32), shape=(K.tf.shape(x)[0], x.shape[1], x.shape[2]))
should be replace with:
case_true = K.tf.reshape(K.tf.zeros([x.shape[0] * x.shape[1] * x.shape[2]], K.tf.float32), shape=(K.tf.shape(x)[0], x.shape[1], x.shape[2]))
or using K.tf.zeros_like:
case_true = K.tf.zeros_like(x)
Workable code:
import keras.backend as K
import numpy as np
def ScoreActivationFromSigmoid(x, target_min=1, target_max=9) :
condition = K.tf.logical_and(K.tf.less(x, 1), K.tf.greater(x, -1))
case_true = K.tf.zeros_like(x)
case_false = x
changed_x = K.tf.where(condition, case_true, case_false)
activated_x = K.tf.sigmoid(changed_x)
score = activated_x * (target_max - target_min) + target_min
return score
with K.tf.Session() as sess:
x = K.tf.placeholder(K.tf.float32, shape=(1028, 300, 64), name='x')
score = sess.run(ScoreActivationFromSigmoid(x), feed_dict={'x:0':np.random.randn(1028, 300, 64)})
print(score)

Add Multiple specific time in crontab by python programming

I want to add multiple time( at hour like 12,13,14) in crontab using python2.7.8. How can I do that .
for job in cron.find_comment(cron_id):
job.hour.on(int ('5'))
job.minute.on(int ('30'))
"""It displaying
"30 5 * * * '/export/home/www/current/abc.sh' # IMPORT_TUD
"
"""
#And I am trying to do like....
for job in cron.find_comment(cron_id):
job.hour.on(int ('5,6,7'))
job.minute.on(int ('30'))
"""Output should be like this..
"30 5,6,7 * * * '/export/home/www/current/abc.sh' # IMPORT_TUD
"
But It's not working """
This is code working for single hour entry.... Its working fine but now I have
time like this ['13:00:00','14:00:00','15:00:00']
if daily_job > 0:
sched_str = sched_str.replace(r'",', r",") # this replaces ", with ;
sched_str = sched_str.replace(r'"', '')
time_str = sched_str.split(':')
for job in cron.find_comment(cron_id):
job.hour.on(int(time_str[0]))
job.minute.on(int(time_str[1]))
I found two approach:
1. If we want No. times = No. of cronTab entry like...
30 3 * * * '/etc/crontab/abc.sh' # hello
30 4 * * * '/etc/crontab/abc.sh' # hello
30 5 * * * '/etc/crontab/abc.sh' # hello
file_cron.remove_all(comment='hello')
for i in sched_str:
time_str = i.split(':')
cur_hour = int (time_str[0])
cur_minute = int (time_str[1])
cron_job = file_cron.new('/etc/crontab', comment='hello')
cron_job.hour.on(cur_hour)
cron_job.minute.on(cur_minute)
file_cron.write()
2. For single line of cronTab like (30 3,4,5,6 * * *'/etc/crontab/abc.sh' # hello)
file_cron = CronTab(tabfile='filename.tab')
sched_hour = ['11','13','15']
def one():
cron_job.hour.on(sched_hour[0])
def two():
cron_job.hour.on(sched_hour[0],sched_hour[1])
def three():
cron_job.hour.on(sched_hour[0],sched_hour[1],sched_hour[2])
options = {1: one,
2: two,
3: three,
}
a = len(sched_hour)
for cron_job in file_cron.find_comment('hello'):
options[a]()
cron_job.minute.on(40)
file_cron.write()

code for split a list of items into list (split function) in python

I have a function to split the list,
example
def split(*arg):
row = len(arg[0])
col = len(arg)
new = [row * col]
for i in row:
for j in col:
new[j][i] = arg[i][j]
return new
# this is method for split the list but it is include errors
Desired output:
list_a = [(1,2,3),(8,9,10),(100,20,15)]
split (list_a)
[(1,8,100),(2,9,20),(3,10,15)]
This is very similar to Transpose nested list in python.
However, you want a list of tuples as the result, so we don't even need a list comprehension. Just
list_a = [(1,2,3),(8,9,10),(100,20,15)]
zip(*list_a) # Python 2
# or
list(zip(*list_a)) # Python 3
# [(1, 8, 100), (2, 9, 20), (3, 10, 15)]
This uses argument unpacking and the built-in zip function.
based on the desired output it seems you are trying to find the transpose so you could do it with numpy like this:
import numpy
list_a = [(1,2,3),(8,9,10),(100,20,15)]
transpose_a = numpy.transpose(list_a)
print(transpose_a)
#or
#print(list(transpose_a))
But your split is malfunctioning for a few reasons reasons:
you are using *arg perameter but not unpacking the argument so you need to call it like split(*list_a)
new = [row * col] is creating a new list with one item instead of a two dimensional list.
you are iterating over integers instead of using range(row) and range(col).
row and col need to be swapped: row = len(arg) and col = len(arg[0]) since you use row as first dimension and col as second.
Although it occurs to me that this is what zip is designed to do so maybe you just need to use that instead.

append items multiple times to a list in a First Item First multiple order

this is what I want to accomplish:
alist = ['item_a1','item_a2']
blist = ['item_b1','item_b2']
final_list = []
I want the final list to be:
final_list = [['item_a1','item_a2'],['item_a1','item_a2'],['item_b1','item_b2'],['item_b1','item_b2']]
I know I can do it with the following clumsy codes:
i = 0
while i < 2:
final_list.append(alist)
i += 1
#then run it again with final_list.append(blist)
but is there a more elegant way of doing this?
i figured it out my self:
final_list = [alist] * 2 + [blist] * 3