【问题标题】:Checking to see if two values are the same in an array. Python检查数组中的两个值是否相同。 Python
【发布时间】:2018-01-03 15:35:17
【问题描述】:

这是我的代码

a = [1, "A", 2, "B", 1, "C"]
empty = []
if a[0] == a[2]:
    empty.append(a[1])
    empty.append(a[3])
elif a[0] == a[4]:
    empty.append(a[1])
    empty.append(a[5])
elif a[2] == a[4]:
    empty.append(a[3])
    empty.append(a[5])

我正在寻找一种更有效的方法来执行此过程。如果该数组中的两个元素 [整数] 相同,我希望它将数组 [索引 + 1] 附加到“空”中。如果数组中有 2 个相同的值,它将有 2 个字母。 在此示例中,它将是 ["A","C"],因为它们都有 1。我更愿意找到重复项目所在位置的索引位置。

【问题讨论】:

  • 由于“缩进错误”而没有让我发帖。”是什么意思?据我所知,SO 从不进行任何缩进测试(不幸的是,有很多用户发布了完全未缩进的代码)。
  • 不要指望其他人为了解决您的问题而从屏幕截图中转录您的代码。 拥有代码:将其粘贴到您的问题中。
  • @WillemVanOnsem 查看图片中的代码。我发布了完全相同的内容并不断抛出一个红色错误
  • @khelwood 如果它成功了我会的!它不让我发帖

标签: python arrays


【解决方案1】:

如果你只想找到一个匹配项

a = [1, "A", 2, "B", 1, "C"]
empty = []
match = False

for i in range(0, len(a), 2):
    for j in range(i + 2, len(a) - 1, 2):
        if a[i] == a[j]:
            empty.append(a[i])
            empty.append(a[j])
            match = True
            break
    if match:
        break

如果你想要所有匹配项

a = [1, "A", 2, "B", 1, "C"]
empty = []

for i in range(0, len(a), 2):
    for j in range(i + 2, len(a) - 1, 2):
        if a[i] == a[j]:
            empty.append(a[i])
            empty.append(a[j])

如果您希望索引而不是项目更改

empty.append(a[i])
empty.append(a[j])

empty.append(i)
empty.append(j)

编辑

正如@Aaron 所指出的,可以使用for 循环的else 子句编写带有匹配变量的代码。

a = [1, "A", 2, "B", 1, "C"]
empty = []

for i in range(0, len(a), 2):
    for j in range(i + 2, len(a) - 1, 2):
        if a[i] == a[j]:
            empty.append(a[i])
            empty.append(a[j])
            break
    else:
        continue
    break

【讨论】:

  • 你能找到数组中相同数字的索引吗,所以在 a = [1, "A", 2, "B", 1, "C"] 中,它会是索引,[0] 和索引 [4]
  • @off-white 立即查看我的答案
  • 要在第一个示例中消除无关变量match,您可以在内部循环之后使用else: continue \n break
  • @Aaron 没有想到这一点。我会把它添加到我的答案中
  • for: else: 是很多人经常忘记的东西,有时它非常有用
【解决方案2】:

试试这个检查重复项

>>> def checkDuplicate(List):
    duplicate={}
    for i in List:
            ## checking whether the item is already present in dictionary or not
            ## increasing count if present
            ## initializing count to 1 if not present

        duplicate[i]=duplicate.get(i,0)+1

    return [k for k,v in duplicate.items() if v>1]

>>> checkDuplicate([1,2,3,"s",1,2,3])
[1, 2, 3]

【讨论】:

    【解决方案3】:

    您可以使用itertools.combinations 从列表(在本例中为偶数索引列表)中获取两个项目的每个唯一组合。项目将按输入的字典顺序生成,因此如果输入已排序,则输出也将排序。

    from itertools import combinations
    a = []
    empty = [1, "A", 2, "B", 1, "C"]
    for x,y in combinations(range(0,len(a),2),2): #take combinations in sets of 2 from the even indices
        if a[x] == a[y]:
            empty += (a[x+1], a[y+1]) #this could fail if you have an odd number of items in the list a

    如果您想在匹配单个配对后停止,只需在“if”语句中将项目附加到empty 后添加break

    【讨论】:

      猜你喜欢
      • 2014-02-03
      • 2023-04-07
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 2020-02-12
      相关资源
      最近更新 更多