python - 如何将用户输入转换为列表并删除所有出现的特定数字或字符?

标签 python list type-conversion raw-input

我认为我从错误的角度解决这个问题,或者缺乏对内置函数和语法的正确理解来解决我的问题,尽管我尝试过。我还发现使用:

input("Enter input: ")

很危险,应该使用 raw_input 代替,但似乎无法正常运行。

我想编写一个脚本,它可以接受用户输入,将其转换为列表,将每个元素乘以 3,扫描该问题的解决方案以查找任何“3”,并删除所有出现的“3”,同时保留所有列表中各自元素中的其他数字,然后打印或返回最终结果。

例如。输入 1 2 3 将输出 6 9,即 1 * 3 = 3,该值将被省略。 前任。输入 2 6 11 将输出 6 18 作为 11 * 3 = 33,并且两个 3 将被省略。

例如,如果用户输入 x,其中 x * 3 = 2381193 - 我希望将其转换为 28119。

我相信最简单的方法是转换为字符串?

我从这样的事情开始:

userInput = input("list element seperated by space: ")
nums = userInput.split()
x = int(nums[0]) * 3
y = int(nums[1]) * 3
z = int(nums[2]) * 3
output = x, y, z
negate = list(output)
if "3" in str(x):
    del negate[0]
    if "3" in str(y):
        del negate[1]
            if "3" in str(z):
                del negate[2]
print(negate)

现在我重新考虑了:

userInput = raw_input("list element seperated by space: ")
nums = userInput.split()

for x in list(nums):
numsList = int(x) * 3
output = list(numsList)

y = "3"
while y in str(output): output.remove(y)
print(output)

但总的来说,我无法达到预期的结果。

您能提供反馈吗?

我们将不胜感激:)

最佳答案

就您而言,您的第一个片段已经接近解决您的问题。您唯一想做的就是将条件语句更改为交互式语句,如下所示:

nums = str(input("list element seperated by space: ")).split(" ")
num_list = []
if len(nums) != 1:
    num_list = [*(int(num.replace("3", "")) * 3 for num in nums)]
else:
    num_list = [nums[0]]
for x in num_list:
    if x != 3:
        print(str(x).replace("3", "") + " ", end="")
    else:
        print("0 ", end="")

If you input 11 you would receive 0 and if for instance you had 133 - you would want to remove the 3 but keep the 1.

你的问题的这一部分不够清晰/详细,因此我没有在上面的代码片段中包含这个逻辑。因此,一旦上述观点明确,任何人都可以自由编辑我的答案并将其包含在内。

[编辑]:所以我对上面的代码片段进行了更改。我还没有测试过这个,所以它有可能是错误的。如果是这种情况,请告诉我任何可能以不需要的方式结束的特定模式/测试。

关于python - 如何将用户输入转换为列表并删除所有出现的特定数字或字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52795005/

相关文章:

java - 如何在 Instream 或列表流中添加增量值?

python-3.x - 为什么Python在这段看似简单的代码中不拼接换行符呢?

c# - 在 C# 中将 System.Web.UI.WebControls.Unit 转换为 int

arrays - 数组到字典(无循环)

Java:将原始 boolean 值转换为原始 int (0,1) 的好方法

python - Pandas 可以按行执行 min() 和 max() 函数吗?

python - 转换小数点分隔符

python - 如何将 Pandas 中的变量指定为序数/分类?

python - MySQLdb 和 Python ImportError

c# - Streamwriter 仅从字符串列表中写入一定数量的字节