0
str1= ",".join(str(e) for e in paths)
str2= ",".join(str(e) for e in newlist)
print(str1)
print(str2) 
for j in str2:
    for i in str1:
        if (j[0]==i[0]): 
        print('number is {}'.format(i))

嘿,我正在制作程序,我需要访问列表元素的特定数字,例如如果一个列表是 [12,23,34] 而另一个是 [13,34],我想访问第一个元素,即 12 的数字,即 1 & 2并将其与另一个列表进行比较,如果出现任何相等的数字,我想打印第一个列表的第一个元素。就像在我们的示例中 12 和 13 有 1 作为相等的数字我想打印 12。我尝试了几天但卡住了。而且我尝试将它转换为字符串然后也出现了一些问题。

在上面的例子中,我得到这样打印的特定数字:

number is 1
number is 3
number is 3
number is ,
number is ,
number is 1
number is 4

我不想要“逗号”,如果发生匹配,则应按照示例中的说明打印数字。任何帮助将不胜感激。

谢谢。

4

4 回答 4

1

将它们保留为列表不是更容易使用吗?
如果您只想比较相同的索引,那么:

In []:
l1 = [12,23,34]
l2 = [13,34]
for a, b in zip(l1, l2):
    if a//10 == b//10:
        print(a)

Out[]:
12

或者您想检查任何索引:

In []:
import itertools as it

l1 = [12,23,34]
l2 = [13,34]
for a, b in it.product(l1, l2):
    if a//10 == b//10:
        print(a)

Out[]:
12
34
于 2018-04-30T05:53:59.203 回答
0

这应该适用于您的用例

list1 = [123, 12, 32232, 1231]
list2 = [1232, 23243, 54545]

def find_intersection(list1, list2):
    list2_digits = set.union(*[get_digits(x) for x in list2])
    for num1 in list1:
        digits1 = get_digits(num1)
        for num2 in list2:
            digits2 = get_digits(num2)
            if digits1.intersection(digits2):
                print 'Found Match', num1, num2  # We found a match
                # Break here unless you want to find all possible matches

def get_digits(num):
    d = set()
    while num > 0:
        d.add(num % 10)
        num = num / 10
    return d

find_intersection(list1, list2)
于 2018-04-30T05:52:25.950 回答
0

尝试这个

str1= ",".join(str(e) for e in paths)
str2= ",".join(str(e) for e in newlist)
print(str1)
print(str2) 
for j in str2:
    for i in str1:
        if (j[0]==i[0] and (i and j != ',')): 
        print('number is {}'.format(i))

输出

12,23,34
13,34
number is 1
number is 3
number is 3
number is 3
number is 3
number is 4
于 2018-04-30T05:43:17.100 回答
0

我不确定我是否完全理解这个问题,但是:

list1 = [13,23,34]
list2 = [24,18,91]
list1 = list(map(str,list1)) #Map the arrays of ints to arrays of strings
list2 = list(map(str,list2))

for j in list1:
    for i in list2:
        for character in j:
            if character in i:
                print(j+' matches with '+i)
                break

打印出来:

13 matches with 18
13 matches with 91
23 matches with 24
34 matches with 24
于 2018-04-30T05:54:25.257 回答