I want to create a loop of zips I have sample.csv file with the below entries:
> 1 2 3 4
> a b c d
> apple banana cat dog
and have the below code:
sample= open("sample.csv)
lines = sample.readlines()
testcol = []
for l in lines:
zipped = zip(testcol ,l)
The output is:
[(('1','a'),'apple'),(('2','b'),'banana'),(('3','c'),'cat'),(('4','d'),'dog')]
but what i want is:
[('1','a','apple'),('2','b','banana'),('3','c','cat'),('4','d','dog')]
The reason why i have to put it in loops is because my sample.csv may contain arbitrary number of rows.
This should do the job:
sample = open("sample.csv)
lines = [line.split() for line in sample.readlines()] #splitting on whitespace to create list of lists
zipped = zip(*lines)
See Unpacking Argument Lists:
The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple.
Related
I have a function with an optional list of parameters :
cleanFolders(String... folders) {
other_function_called(param1,param2,param3)
}
This function calls another function which take exactly three parameters.
So, I want to use the list of parameters folders to call this other function :
if there is only one element in folders list, I call
other_function_called(folders[0],"none","none")
if there are two elements :
other_function_called(folders[0],folders[1],"none")
and for three elements :
other_function_called(folders[0],folders[1],folders[2])
How I can do this properly (not using many disgracious "if else") ?
Thanks
as Jeff writes, you can use * to unpack the varargs array.
However, this will give you MissingMethodException if the number of arguments is not matching.
For this case you could create a new array starting with the available values, that is then filled up with the remaining default values, so that unpacked it just matches the right number of arguments.
def spreadArgs = args + ["none"] * (3 - args.size())
other_function_called(*spreadArgs)
If I have an input of a tuple containing two lists of integers of the same length, and I want my output to be a list of these two lists zipped, then how do I first extract these two lists from the tuple? For example, if my input is twolists= ([1;2;3], [4;5;6]), then I want my output to be [(1,4); (2,5); (3,6)]. How do I first separate the tuple into (for example) l1= [1;2;3], and l2= [4;5;6]?
You can use pattern matching to get the components of a tuple. For example, this function takes a tuple of two ints and returns their sum:
let add_uncurried tuple =
let (a, b) = tuple in a + b
To put it another way, you can write let (a, b) = tuple in ... to get the components of the tuple under the names a and b.
Given the following list:
colors=['#c85200','#5f9ed1','lightgrey','#ffbc79','#006ba4','dimgray','#ff800e','#a2c8ec'
,'grey','salmon','cyan','silver']
And this list:
Hospital=['a','b','c','d']
After I get the number of colors based on the length of the list - 'Hospital':
num_hosp=len(Hospital)
colrs=colors[:num_hosp]
colrs
['#c85200', '#5f9ed1', 'lightgrey', '#ffbc79']
...and zip the lists together:
hcolrs=zip(Hospitals,colrs)
Next, I'd like to be able to select 1 or more colors from hcolrs if given a list of one or more hospitals from 'Hospitals'.
Like this:
newHosps=['a','c'] #input
newColrs=['#c85200','lightgrey'] #output
Thanks in advance!
Pass the result of zip to the dict constructor to make lookup simple/fast:
# Don't need to slice colors; zip stops when shortest iterable exhausted
hosp_to_color = dict(zip(Hospitals, colors))
then use it:
newHosps = ['a','c']
newColrs = [hosp_to_color[h] for h in newHosps]
I want to write a program which will read in a list of tuples, and in the tuple it will contain two elements. The first element can be an Object, and the second element will be the quantity of that Object. Just like: Mylist([{Object1,Numbers},{Object2, Numbers}]).
Then I want to read in the Numbers and print the related Object Numbers times and then store them in a list.
So if Mylist([{lol, 3},{lmao, 2}]), then I should get [lol, lol, lol, lmao, lmao] as the final result.
My thought is to first unzip those tuples (imagine if there are more than 2) into two tuples which the first one contains the Objects while the second one contains the quantity numbers.
After that read the numbers in second tuples and then print the related Object in first tuple with the exact times. But I don't know how to do this. THanks for any help!
A list comprehension can do that:
lists:flatten([lists:duplicate(N,A) || {A, N} <- L]).
If you really want printing too, use recursion:
p([]) -> [];
p([{A,N}|T]) ->
FmtString = string:join(lists:duplicate(N,"~p"), " ")++"\n",
D = lists:duplicate(N,A),
io:format(FmtString, D),
D++p(T).
This code creates a format string for io:format/2 using lists:duplicate/2 to replicate the "~p" format specifier N times, joins them with a space with string:join/2, and adds a newline. It then uses lists:duplicate/2 again to get a list of N copies of A, prints those N items using the format string, and then combines the list with the result of a recursive call to create the function result.
Let me try to put this in a simple manner.
I have 2 lists, which look like below:
List1 = [('a', 1, 'low'), ('b', 10, 'high')] # --> Tuples in List
List2 = ["('a', 1, 'low')", "('b', 10, 'high')"] # --> Here the Tuples are actually of Type String.
List1 is output of a SQL query. List2 is defined by me as expected result.
I am using Robot Framework to compare these two lists with the Keyword Lists Should Be Equal. But it fails as List2 has strings which look like Tuple.
How can I compare these two lists? Can I convert both the lists to a different variable type so that I can compare them. I am trying to avoid the python coding here.
It's unclear exactly what your data looks like, but since the two lists have different contents you'll have to convert one or both of them to a common format.
You could, for example, convert the first list to a string with something like this:
| ${actual}= | Evaluate | [str(x) for x in ${List1}]
I doubt that gives you exactly what you need because, again, it's unclear exactly what you need. However, the technique remains the same: use Evaluate to write a little bit of python code to convert one of your lists to be the same format as the other list before doing the compare.
This may be the long procedure, i have used tuples (1,2) instead (a,1,low) #( cause name error in python). But you told its getting from SQL. Important is difference between (1,2) and (1, 2) #(space mismatch)
var.py
List1 = [(1,2), (3,4)]
test.robot(txt file)
*** Settings ***
Library BuiltIn
Library Collections
Variables var.py
Library String
*** Variables ***
#{appnd_li}
*** Test Cases ***
TEST
#constructing List2=["(1, 2)","(3, 4)"]
${List2}= Create List (1, 2) (3, 4)
# importing List1 from variable file
${len}= Get Length ${List1}
#initialize empty list
${li}= Create List #{appnd_li}
:FOR ${I} IN RANGE 0 ${len}
\ ${item}= Convert To String ${List1[${I}]}
\ Append To List ${li} ${item}
Lists Should Be Equal ${li} ${List2}
~