How to separate an input on python into different lists? - python

I have a code in which I require 3 different inputs to be put into separate lists. Currently I have 3 lists set up:
A = []
B = []
C = []
I also currently have 3 different inputs, one for each list, and I wish to combine these inputs into one input, separating each factor of this by a comma or semicolon.
For example:
Apple,365,rope
Using python, how would I separate each factor in the input so they can be put into different lists?
I have tried searching for how to separate using an input but this has not worked as I do not know exactly what the input will be.

Assuming that your input is on the command line using the input() function, you can do the following:
A = []
B = []
C = []
# let's say you input "Apple,365,rope"
my_input = input()
# we split it on each commma into a list -> ["Apple", "365","rope"]
split_input_list = myinput.split(',')
# finally we put each input into the respective list
A.append(split_input_list[0])
B.append(split_input_list[1])
C.append(split_input_list[2])

A = []
B = []
C = []
# if string
your_input = "Apple,365,rope"
your_input = your_input.split(",")
A = [your_input[0]]
B = [your_input[1]]
C = [your_input[2]]
print A, B, C
# if tuple
your_input = ("Apple", "365" , "rope")
A = [your_input[0]]
B = [your_input[1]]
C = [your_input[2]]
print A, B, C

Related

Extract key1:value1 from dictionary 1 and key1:value1 from dictionary 2, assign them to 4 different variables, loop

What I need to do:
for each key in dictionary1 extract key1:value1 from dictionary1 and key1:value1 from dictionary2
assign those 2 pairs to 4 different variables
use those variables in other methods
move on to the next iteration (extract key2:value2 of both dictionaries 1 and 2, and assign to the same 4 variables)
Example:
d_one = {1:z, 2:x, 3:y}
d_two = {9:o, 8:n, 7:m}
the result has to be
a = 1
b = z
c = 9
d = o
(calling some other methods using those variables here)
(moving on to the next iteration)
a = 2
b = x
c = 8
d = n
(and so on)
My brain is overloaded on this one. Since I can't nest for loops to accomplish this task, I guess the correct usage of 'and' statement should do it? I have no idea how so I try to split it up...
d_one = {'1':'z', '2':'x', '3':'y'}
d_two = {'9':'o', '8':'n', '7':'m'}
for i in range(0, len(d_one)):
for a in list(d_one.keys())[i]:
a = d_one.keys()[i]
b = d_one[a]
for c in list(d_two.keys())[i]:
c = d_two.keys()[i]
d = d_two[c]
print(a, b, c, d)
output:
TypeError: 'dict_keys' object is not subscriptable
Try this:
d_one = {'1':'z', '2':'x', '3':'y'}
d_two = {'9':'o', '8':'n', '7':'m'}
for (a,b), (c,d) in zip(d_one.items(), d_two.items()):
print(a, b, c, d)

split or chunk dynamic string into specific parts and merging in python

Is there way to split or chunk the dynamic string into fixed size? let me explain:
Suppose:
name = Natalie
Family = David12
length = len(name) #7 bit
length = len(Family) # 7 bit
i want to split the name and family into and merging as :
result=nadatavilid1e2
and again split and extract the the 2 string as
x= Natalie
y= david
another Example:
Name = john
Family= mark
split and merging:
result= jomahnrk
and again split and extract the the 2 string as
x=john
y= mark
.
Remember variable name and family have different size length every time not static! . i hope my question is clear. i have seen some related solution about it like here and here and here and here and here and here and here but none of these work with what im looking for. Any suggestion ?? Thanks
i'm using spyder python 3.6.4
I have try this code split data into two parts:
def split(data):
indices = list(int(x) for x in data[-1:])
data = data[:-1]
rv = []
for i in indices[::-1]:
rv.append(data[-i:])
data=data[:-i]
rv.append(data)
return rv[::-1]
data='Natalie'
x,c=split(str(data))
print (x)
print (c)
Given you have stated names will always be of equal length you could use wrap to split in to 2 char pairs and the zip and chain to join them up. In the split part you can again use wwrap to split in 2 char pairs but if the number of pairs is odd then you need to split the last pair into 2 single entries. something like.
from textwrap import wrap
from itertools import chain
def merge_names(name, family):
name_split = wrap(name, 2)
family_split = wrap(family, 2)
return "".join(chain(*zip(name_split, family_split)))
def split_names(merged_name):
names = ["", ""]
char_pairs = wrap(merged_name, 2)
if len(char_pairs) % 2:
char_pairs.append(char_pairs[-1][1])
char_pairs[-2] = char_pairs[-2][0]
for index, chars in enumerate(char_pairs):
pos = 1 if index % 2 else 0
names[pos] += chars
return names
print(merge_names("john", "mark"))
print(split_names("jomahnrk"))
print(merge_names("stephen", "natalie"))
print(split_names("stnaeptaheline"))
print(merge_names("Natalie", "David12"))
print(split_names("NaDatavilid1e2"))
OUTPUT
jomahnrk
['john', 'mark']
stnaeptaheline
['stephen', 'natalie']
NaDatavilid1e2
['Natalie', 'David12']
Something like:
a = "Eleonora"
b = "James"
l = max(len(a), len(b))
a = a.lower() + " " * (l-len(a))
b = b.lower() + " " * (l-len(b))
n = 2
a = [a[i:i+n] for i in range(0, len(a), n)]
b = [b[i:i+n] for i in range(0, len(b), n)]
ans = "".join(map(lambda xy: "".join(xy), zip(a, b))).replace(" ", "")
Giving for this example:
eljaeomenosra

is this the method for comparing an interger which i made it str to check if is a string List?

i am trying to compare an "i" counter whitch is interger with a list whitch inludes str numbers , and add it in a string variable
LPL = ["1","2","3"]
f = str()
for i in range (x):
if str(i) == LPL[i]:
f+=str(i)
i expected the f variable had the result of the comparsion: f = 123
List index starts from 0:
LPL = ["1","2","3"]
s = ""
for i in range(1,len(LPL)+1):
if i == int(LPL[i-1]):
s+=str(i)
print(s)
Note that you should use a range from a number to a number and also that python indexes starts from 0, so you need to adapt the code in a way like:
LPL = ["1","2","3"]
f = str()
for i in range (1, len(LPL)+1):
### note that your LPL[0] == 1 and not LPL[1] == 1, so you need to decreasee a number here, that's why a +1 in the range too
if str(i) == LPL[i-1]:
f+=str(i)
### OUTPUT
>>> f
'123'
Perhaps I missing something, but if you wish to combine the elements of the list, either by conjoining strings or adding integers, consider using reduce:
LPL = ["1","2","3"]
LPL2 = [1,2,3]
f = reduce(lambda a,b : a+b, LPL) # "123"
f_int = reduce(lambda a,b : a+b, LPL) # 6

Python 2D array with same values

I am a beginner programmer and I am doing a task for school. The task is to assign 4 constant variables and then use a code to work out the value. Each value has a corresponding letter and the program is asking the user to type in 5 numbers then the program will return the word. The code is the following:
array = [["L","N"], #define the 2d array, L=Letters, N=Numbers
["-","-"]] #line for space
a = 2#define the variables
b = 1
c = 7
d = 4
e = (a*b)+b#calcualtions
f = c+b
g = (d/a)-b
h = c*a
i = a+b+d
j = c-a
k = c-d*f
l = c+a
m = (c*a)-b
n = a*d
o = a+d-b
p = (c*d)-a*(b+d)
q = a*(c+(d-b))
r = (d*d)-b
s = r-f-g
array.append(["e",e])
array.append(["f",f])
array.append(["g",g])#append all the calculations
array.append(["h",h])
array.append(["i",i])
array.append(["j",j])
array.append(["k",k])
array.append(["l",l])
array.append(["m",m])
array.append(["n",n])
array.append(["o",o])
array.append(["p",p])
array.append(["q",q])
array.append(["r",r])
array.append(["s",s])
def answer():
len_row = len(array)
number_input = int(input("Enter number: "))
for i in range(len_row):
if number_input == (array[i][1]):
return array[i][0]
break
one_let = answer()
two_let = answer()
thr_let = answer()
fou_let = answer()
fiv_let = answer()
print(one_let,two_let,thr_let,fou_let,fiv_let)
The numbers that I am meant to put in are 6, 18,, 7, 8, and 3.
The word that prints is "spife" and the word that is meant to be printed is "spine". The problem is that there are two letters that have a variable of 8 and Python gets the first one only. Is there a way to print out the two seperate words but first with the first variable in a 2D array and second with the second 2D array? i.e spife then spine
Thank you for your help ahead, I am just a beginner! :)
Yes you can do it but is a bit tricky the secret is to use itertools.product on the list of letters that could have each of the five values.
First you need to use a better data structure such as a dict, (in this case a collection.defaltdict) to hold the letters that have some value. You can do this way:
import collections
import itertools
a = 2#define the variables
b = 1
c = 7
d = 4
e = (a*b)+b#calcualtions
f = c+b
g = (d/a)-b
h = c*a
i = a+b+d
j = c-a
k = c-d*f
l = c+a
m = (c*a)-b
n = a*d
o = a+d-b
p = (c*d)-a*(b+d)
q = a*(c+(d-b))
r = (d*d)-b
s = r-f-g
dat = collections.defaultdict(list)
for c in "abcdefghijklmnopqrs":
dat[eval(c)].append(c)
Now in dat you have a list of letters that match some number, for example
print(dat[6])
print(dat[18])
print(dat[7])
print(dat[8])
print(dat[3])
Outputs:
['s']
['p']
['i']
['f', 'n']
['e']
OK, then you need to change answerto return a list of letters, and collect the user input:
def answer():
number_input = int(input("Enter number: "))
return dat[number_input]
letts = [answer() for _ in range(5)] #collect five answers of the user
And the final magic is done here:
for s in map(lambda x: "".join(x),itertools.product(*letts)):
print(s)
Now if you are confused then study:
collections
collections.defaultdict
itertools
itertools.product
str.join

writing a range output lists into a text file or four array

I have a function and its output is a selection of lists [a,b,c,d] [a,b,c,d] [a,b,c,d] [a,b,c,d]
and I want [a,a,a,a] [b,b,b,b] [c,c,c,c] [d,d,d,d]
def meanarr(image, res=None):
"construct code which runs over a single ccd to get the means"
a = pyfits.getdata(image).MAG_AUTO
q = numpy.mean(a)
s = pyfits.getdata(image).X2WIN_IMAGE
j = numpy.mean(s)
f = pyfits.getdata(image).Y2WIN_IMAGE
z = numpy.mean(f)
g = pyfits.getdata(image).XYWIN_IMAGE
h = abs(numpy.mean(g))
a = [q, j, z, h]
print a
s0 = ''
return res
for arg in sys.argv[1:]:
#print arg
s = meanarr(arg)
This is my function and program how would I get the code to read all of the q's in one list all of the j's z's and h's in their own lists. I know I could separate the function into four different functions but this still doesn't return my results in a list it just outputs them individually.
You might be looking for zip. Try that :
data = [['a','b','c','d'], ['a','b','c','d'], ['a','b','c','d'], ['a','b','c','d']]
print data
print zip(*data)
You can write it this way:
def meanarr(image, res=None):
"costruct code which runs over a single ccd to get the means"
a=pyfits.getdata(image).MAG_AUTO
q=numpy.mean(a)
s=pyfits.getdata(image).X2WIN_IMAGE
j=numpy.mean(s)
f=pyfits.getdata(image).Y2WIN_IMAGE
z=numpy.mean(f)
g=pyfits.getdata(image).XYWIN_IMAGE
h= abs(numpy.mean(g))
a=[q,j,z,h]
return a
data =[meanarr(arg) for arg in sys.argv[1:]]
print zip(*data)

Categories