1

I am trying to convert list of list to LIST using robot framework keywords.Output of my script in log file was like this :

@{ListA} = [ [a, b] | [c, d, e] | f | g] 

I wanted to flatten this list as

 [ a , b , c , d , e , f , g]

How to convert this?

Any suggestions would be helpful. Thanks.

4
  • In the code in your question you aren't creating a list. More accurately, you're creating a list with one element,which is a string that looks like "[ (a,b), ...]". Do you have an actual list-of-lists, or do you literally want to transform this string to a list of lists, and then flatten it out? Commented Jul 26, 2016 at 11:19
  • @BryanOakley , I meant to say that output of my script was as: @{ListA} = [ [a, b] | [c, d, e] | f | g] I wanted to flatten this list as [ a | b | c | d | e | f | g] Commented Jul 26, 2016 at 11:48
  • That is even less precise of an answer. The pipes isn't valid python syntax or robot syntax. Commented Jul 26, 2016 at 11:53
  • what are "a", "b", etc? Are they supposed to be strings? Commented Jul 26, 2016 at 12:56

1 Answer 1

3

List comprehensions are quite powerful, and can be used with the Evaluate keyword. Here you can force each item to be a list by checking to see if it already is - the "(sublist if isinstance(sublist, list) else [sublist])" part. Once you have a list of lists, you can flatten that with the nesting ability of a list comprehension.

Some folks frown upon type-checking in Python, but one of the struggles is that strings and lists can be mistaken. Here a direct type-check is used. There are other approaches to check if an object is a list and you can modify this as needed.

List of lists and Other Items
    @{InnerA}    Create List    a    b
    @{InnerB}    Create List    c    d    e
    @{ListA}    Create List    ${InnerA}    ${InnerB}    f    g
    ${flat}    Evaluate    [item for sublist in $ListA for item in (sublist if isinstance(sublist, list) else [sublist])]
    Log List    ${flat}

_

INFO : @{InnerA} = [ a | b ]
INFO : @{InnerB} = [ c | d | e ]
INFO : @{ListA} = [ [u'a', u'b'] | [u'c', u'd', u'e'] | f | g ]
INFO : ${flat} = [u'a', u'b', u'c', u'd', u'e', u'f', u'g']
INFO : 
List length is 7 and it contains following items:
0: a
1: b
2: c
3: d
4: e
5: f
6: g
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.