在Python中按1取1的元素时如何串联两个列表?
示例:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
预期结果:
>>> joinedlist
[1, 4, 2, 5, 3, 6]
答案 0 :(得分:4)
import {useState} from 'react';
export const Accordion = ({ text, limit = 100 }) => {
const isExpandable = text.length > limit;
const [viewText, setViewText] = useState(
isExpandable ? text.slice(0, limit) : text
);
const isExpanded = text.length === viewText.length;
return (
<>
<p>{viewText}</p>
{isExpandable && (
<button
onClick={() => setViewText(isExpanded ? text.slice(0, limit) : text)}
>
{isExpanded ? "show less" : "show more"}
</button>
)}
</>
);
};
列表,并用itertooos.chain
展平:
zip
答案 1 :(得分:2)
这是一种简单的方法:
x = []
for a in zip(listone,listtwo):
x.extend(a)
x
或者,如果您希望从itertools获得一些带有链条的黑魔法:
list(chain(*zip(listone,listtwo)))
答案 2 :(得分:2)
仅使用list_comprehensions
而没有其他任何精美的库,您可以这样做:
In [825]: [j for i in zip(listone, listtwo) for j in i]
Out[825]: [1, 4, 2, 5, 3, 6]
答案 3 :(得分:1)
这是另一种方式:
joinedlist = [x for pair in zip(listone, listtwo) for x in pair]
答案 4 :(得分:1)
您有很多选择来获得期望的输出。
x = []
for a in zip(listone, listtwo):
for b in a:
x.append(b)
x = []
for a in zip(listone, listtwo):
x.append(a[0])
x.append(a[1])
x = [x for i in zip(listone, listtwo) for x in i]
如果您为每个点打印x
,则输出将为:[1, 4, 2, 5, 3, 6]