如何访问python中列出元素的特定数字?

时间:2018-04-30 05:31:32

标签: python python-2.7 list

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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)

答案 3 :(得分: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