有条件循环

时间:2018-07-13 05:02:15

标签: python python-3.x loops

我想用条件循环。

In [1]  : data_1
Out [1] :
text1
text2

In [2]  : data_2
Out [2] :
a
b
c
d
e

我希望data_1中的每个文本只能用于data_2中的2个文本。因此,输出将是这样。

text1, a
text1, b
text2, c
text2, d

,如果data_1没有任何数据,它将停止。我这样输入脚本,但是没有用。

for i in range(len(data_1)):
    for j in range(0, len(data_2)):
            print(i, j)

输出显示如下。

0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4

5 个答案:

答案 0 :(得分:3)

一种方法是使用itertools库和zip(),例如:

In []:
import itertools as it
n = 2   # No. of repetitions
list(zip(it.chain.from_iterable(it.repeat(x, n) for x in data_1), data_2))

Out[]:
[('text1', 'a'), ('text1', 'b'), ('text2', 'c'), ('text2', 'd')]

或者如果您想print()淘汰每个元素,则:

In []:
for x in zip(it.chain.from_iterable(it.repeat(x, n) for x in data_1), data_2):
    print(', '.join(x))

Out[]:
text1, a
text1, b
text2, c
text2, d

答案 1 :(得分:1)

data_1 = ['text1','text2']
data_2 = ['a','b','c','d','e']

print '\n'.join([data_1[i//2]+','+data_2[i] for i in range(min(len(data_1)*2,len(data_2)))])

输出:

text1,a
text1,b
text2,c
text2,d

更笼统的

from math import ceil
data_1 = ['text1','text2']
data_2 = ['a','b','c','d','e','f','g']

t = int(ceil(len(data_2)/float(len(data_1))))
print '\n'.join([data_1[i/t]+','+d for i,d in enumerate(data_2)])

只要data_1短于data_2,这将起作用

Output:

text1,a
text1,b
text1,c
text1,d
text2,e
text2,f
text2,g

答案 2 :(得分:1)

这是一种简单的方法(尽管比AChampion少了pythonic的方法)来实现您想要的目标:

ind = 0
for i in data_1:
    for _ in range(2):
        print('{}, {}'.format(i, data_2[ind]))
        ind += 1

答案 3 :(得分:0)

data_1 = ['text1','text2']
data_2 = ['a','b','c','d']

for i in range (len(data_1)):
    if i == (len(data_2)/2 -1):
        k=i+1
        data_2 = data_2[k:]
        for j in range(len(data_1)):
            print (data_1[i],data_2[j])
    else:
        for j in range(len(data_1)):
            print (data_1[i],data_2[j])

答案 4 :(得分:0)

也许不太花哨的方法是将data_1加倍:

data_1 = ['text1','text2', 'text3', 'text4', 'text5', 'text6']
data_2 = ['a','b','c','d', 'e,', 'f', 'g']

double_data_1 = []
[ double_data_1.append(e) for e in data_1 for ee in range(2) ]
res = zip(double_data_1, data_2)
list(res)

[('text1', 'a'),
 ('text1', 'b'),
 ('text2', 'c'),
 ('text2', 'd'),
 ('text3', 'e,'),
 ('text3', 'f'),
 ('text4', 'g')]