How do I concatenate two lists in Python?

前端 未结 25 2375
时光取名叫无心
时光取名叫无心 2020-11-21 06:18

How do I concatenate two lists in Python?

Example:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

Expected outcome:

>&g         


        
25条回答
  •  野性不改
    2020-11-21 06:42

    As already pointed out by many, itertools.chain() is the way to go if one needs to apply exactly the same treatment to both lists. In my case, I had a label and a flag which were different from one list to the other, so I needed something slightly more complex. As it turns out, behind the scenes itertools.chain() simply does the following:

    for it in iterables:
        for element in it:
            yield element
    

    (see https://docs.python.org/2/library/itertools.html), so I took inspiration from here and wrote something along these lines:

    for iterable, header, flag in ( (newList, 'New', ''), (modList, 'Modified', '-f')):
        print header + ':'
        for path in iterable:
            [...]
            command = 'cp -r' if os.path.isdir(srcPath) else 'cp'
            print >> SCRIPT , command, flag, srcPath, mergedDirPath
            [...]
    

    The main points to understand here are that lists are just a special case of iterable, which are objects like any other; and that for ... in loops in python can work with tuple variables, so it is simple to loop on multiple variables at the same time.

提交回复
热议问题