bash - linux bash 中 python zip() 函数的等价物是什么?

标签 bash loops

<分区>

我想在 bash 中迭代成对的元素。在 Python 中,这是直截了当的:

x_list = [1, 2, 3, 4]
y_list = ["a", "b", "c", "d"]

for x, y in zip(x_list , y_list):
    # here we have access to the values (i.e. the pairs are assigned to variables):
    result = do_something(x, y)
    print(result)

如何在 bash 中复制这样的行为?我需要将对的值存储到 for 循环内的变量中,以便我可以执行一些操作。它应该是这样的:

for x, y in 1a 2b 3c 4d
  do 
     python script.py --x_value=${x} --y_value=${y}
  done

请注意,列表的元素也可以是复杂的东西,例如: x_list = [1e-5, 1e-4, 1e-3]y_list = [10, 20, 30]

最佳答案

您的代码的可能翻译是:

#!/bin/bash

x_list=(1 2 3 4)
y_list=(a b c d)

for i in "${!x_list[@]}"
do
    x=${x_list[i]}
    y=${y_list[i]}
    printf '%q %q\n' "$x" "$y"
done
1 a
2 b
3 c
4 d

但它依赖于两个新创建的数组将具有相同索引的事实。这是问题的说明:

#!/bin/bash

x_list=(1 2 3 4)
y_list=(a b c d)

unset x_list[0] y_list[1]

for i in "${!list0[@]}"
do
    x=${x_list[i]}
    y=${y_list[i]}
    printf '%q %q\n' "$x" "$y"
done
2 ''
3 c
4 d

关于bash - linux bash 中 python zip() 函数的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71529821/

相关文章:

python - 如何根据条件检查两行并将其合并为python中的单行

java - JOptionPane 对话框 - 存在额外行的问题

linux - 继续远程 bash 脚本

bash - 如何将复杂的文件 glob 传递给子 shell?

linux - 可变长度表的 Bash 列总和

linux - 通过从文件中的每一行获取两个参数来循环的 Shell(bash) 脚本

linux - 使用 grep 和 sed 递归查找和替换所有文件中的字符串

python - 在 BASH 中计算持续时间的优化方法

java:字符串索引超出范围:6

sql - 使用 squirrel 的 SQL 中的 DB2 存储过程。无法循环播放