从用户输入创建由混合数据类型(即包含字符串,整数和浮点数的数组)组成的x个元素组成的数组的最简单方法是什么
到目前为止,我编写了一些使用for循环的代码,但我想知道是否有一种优化它的方法,并且代码行最少。
puts "how many elements?"
max = gets.to_i
array = []
for i in 0..max - 1
puts "are you entering in a string, an int or a float?"
data_type = gets.chomp
if %W[string STRING String s S].include?(data_type)
puts "enter in a string"
array[i] = gets.chomp
elsif %W[int INT Int i I].include?(data_type)
puts "enter an int"
array[i] = gets.to_i
elsif %W[Float FLOAT float f F].include?(data_type)
puts "enter a float"
array[i] = gets.to_f
end
end
print array
Run Code Online (Sandbox Code Playgroud) 我试图从每个字符串的末尾删除句点、逗号、单引号和双引号。每个字符串都是字符串列表的一部分
string_list= ["cars." , "red" , "orange," , "man'" , "thus:"]
desired_output --->["cars" , "red" , "orange" , "man", "thus"]
Run Code Online (Sandbox Code Playgroud)
我尝试使用列表理解,但我一直在获取布尔值列表而不是所需的输出:
desired_output = [sub[:-1] =='' for sub in string_list[-1] if sub[:-1]== '.' or ',' or '"' or "'" or ':' or ';' ]
Run Code Online (Sandbox Code Playgroud)
不是我想要的输出,但它输出为:
[True, True, True, True, True]
Run Code Online (Sandbox Code Playgroud)
但我认为这是由于更广泛的一点,我不了解格式化语法的方式,即,格式化列表推导式的哪种方式将输出布尔值列表,这将输出所需的效果。如果可以在给出的答案中包含列表理解的语法类型的通用方案,将不胜感激。
我正在处理一串字符alphabet ="AABBBCCCCDDDDDEFGHIJKLMNOPQRSTUVWXYZZZZZZ"我想创建一个 def 来计算字符串中唯一字符的数量和唯一字符的百分比,而不必使用,alphabet.count("A"), alphabet.count"("B"), alphabet.count("C"), etc etc这样我就不必浪费时间将每个字符繁琐地输入到.count()方法中.
我在某种意义上取得了成功,我得到了我想要的输出,但是由于我构建for循环的方式,输出会多次重复每个结果
这是我的代码:
alphabet ="AABBBCCCCDDDDDEFGHIJKLMNOPQRSTUVWXYZZZZZZ"
def count_num_of_uniq_chars(string)
len = string.length
len = len.to_f
for i in 0..len-1
uniq_char=string[i]
puts "uniq_chars --> #{uniq_char}"
count_of_uniq_char = string.count(string[i])
puts "count_of_uniq_char--> #{count_of_uniq_char}"
percent_of_uniq_char = ( (count_of_uniq_char / len) * 100 )
percent_of_uniq_char=percent_of_uniq_char.to_f
puts "there are #{count_of_uniq_char} letter '#{uniq_char}'s in the string which is #{percent_of_uniq_char}% of strings length "
puts
end # loop end
end #def end
count_num_of_uniq_chars(alphabet)
Run Code Online (Sandbox Code Playgroud)
输出为:
uniq_chars …Run Code Online (Sandbox Code Playgroud) 我有一个字符串:
alphabet = "AABBBCCCCDDDDDEFGHIJKLMNOPQRSTUVWXYZZZZZZ"
Run Code Online (Sandbox Code Playgroud)
我想在每次出现字符时列出它的索引。但是,出于我的目的,初始起始索引将是 1 而不是 0。我设法使用以下行对单个字符执行此操作:
list_all_Z = alphabet.chars.each_with_index.select{|indexx,| indexx.eql? "Z" }.map(&:last).map{|get_rid_of_zero,| get_rid_of_zero + 1 }
Run Code Online (Sandbox Code Playgroud)
哪些输出:
print "all the Z's #{list_all_Z}" --> all the Z's [36, 37, 38, 39, 40, 41]
Run Code Online (Sandbox Code Playgroud)
我如何才能完成相同的任务,但对于序列中的每个字母,而无需手动输入每个特定字符
indexx.eql?
Run Code Online (Sandbox Code Playgroud)