我正在使用python 3,我想创建一个新列表,其中第一个列表中的元素的重复次数与第二个列表中各个元素的重复次数相同
例如:
public class MainActivity extends AppCompatActivity {
public void mainlist(){
ArrayList<ListItem> items = new ArrayList<ListItem>();
for(int i = 0; i < items.size(); i++) {
int num = i + 1;
ListItem l = new ListItem("Item " + num, "sub item " + num);
items.add(l);
}
ListView el=(ListView)findViewById(R.id.eventlist);
MyArrayAdapter myArrayAdapter = new MyArrayAdapter(this, items);
el.setAdapter(myArrayAdapter);
myArrayAdapter.notifyDataSetChanged();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainlist();
}
}
向所有人寻求帮助
答案 0 :(得分:5)
单线解决方案
与zip
同时遍历两个列表,并为每个元素创建具有正确长度的子列表。与itertools.chain
一起加入他们:
# from itertools import chain
list(chain(*([l]*n for l, n in zip(char, int))))
输出:
['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c']
答案 1 :(得分:1)
char = ['a', 'b', 'c']
ints = [2, 4, 3]
解决方案1:使用numpy
import numpy as np
result = np.repeat(char, ints)
解决方案2:纯Python
result = []
for i, c in zip(ints, char):
result.extend(c*i)
输出:
['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c']
答案 2 :(得分:0)
使用zip
例如:
c = ['a', 'b', 'c']
intVal = [2, 4, 3]
result = []
for i, v in zip(c, intVal):
result.extend(list(i*v))
print(result)
输出:
['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c']
答案 3 :(得分:0)
具有for循环,非常基本:
results = list()
for k, i in enumerate(integers):
results_to_add = char[k]*i
results.extend(results_to_add)
答案 4 :(得分:0)
char = ['a', 'b', 'c']
rep = [2, 4, 3]
res = [c*i.split(",") for i,c in zip(char, rep )] # [['a', 'a'], ['b', 'b', 'b', 'b'], ['c', 'c', 'c']]
print([item for sublist in res for item in sublist]) # flattening the list
编辑:
使用itertools.chain
的单线:
print(list(chain(*[c*i.split(",") for (i,c) in zip(char, int)])))
输出:
['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c']
答案 5 :(得分:0)
一个使用列表理解和sum(list_, [])
的班轮。
sum([[x]*y for x,y in zip(char_, int_)], [])
>>> char_ = ['a', 'b', 'c']
>>> int_ = [2, 4, 3]
>>> print(sum([[x]*y for x,y in zip(char_, int_)], []))
>>> ['a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c']
替代:
list(itertools.chain.from_iterable([[x]*y for x,y in zip(char_, int_)]))
它看起来比使用itertools更快。
>>> timeit.repeat(lambda:list(itertools.chain.from_iterable([[x]*y for x,y in zip(char_, int_)])), number = 1000000)
[1.2130177360377274, 1.115080286981538, 1.1174913379945792]
>>> timeit.repeat(lambda:sum([[x]*y for x,y in zip(char_, int_)], []), number = 1000000)
[1.0470570910256356, 0.9831087450147606, 0.9912429330288433]