首页 \ 问答 \ Swift:将数组作为值过滤字典(Swift: Filter a Dictionary with Array as Value)

Swift:将数组作为值过滤字典(Swift: Filter a Dictionary with Array as Value)

我是Swift编程的新手。 对于我的特定项目,我试图用一些用户输入过滤字典,字典的值由一个数组组成。

以下是一些示例代码,以及我想要实现的内容:

var dictionary = ["a": ["aberration", "abc"], "b" : ["babel", "bereft"]]

var filteredDictionary = [String: [String]]()

var searchText = "aberration"

//getting the first letter of string
var firstLetter = searchText[searchText.startIndex]

有了这个特定的searchText,我试图得到:

filteredDictionary = ["a": ["aberration"]]

编辑:我想让字典返回第一个字母作为其关键字,以及与searchText匹配的值。 对不起,如果我不清楚。

以下是我尝试过的一些代码,但很明显,我无法使其工作:

filteredDictionary = dictionary.filter{$0.key == firstLetter && for element in $0.value { element.hasPrefix(searchText) }}

任何帮助,将不胜感激。 谢谢。


I'm new to Swift programming. For my particular project, I'm trying to filter a dictionary with some user input, and the dictionary's value consists of an array.

Here is some sample code, and what I'm trying to accomplish:

var dictionary = ["a": ["aberration", "abc"], "b" : ["babel", "bereft"]]

var filteredDictionary = [String: [String]]()

var searchText = "aberration"

//getting the first letter of string
var firstLetter = searchText[searchText.startIndex]

With this particular searchText, I'm trying to get:

filteredDictionary = ["a": ["aberration"]]

Edit: I want the dictionary to return with the first letter as its key, and the values with what searchText matches up with. Sorry if it I wasn't clear.

Here is some code I have tried, but obviously, I can't get it to work:

filteredDictionary = dictionary.filter{$0.key == firstLetter && for element in $0.value { element.hasPrefix(searchText) }}

Any help would be appreciated. Thanks.


原文:https://stackoverflow.com/questions/48089253
更新时间:2023-08-09 21:08

最满意答案

基于JewelSeaAnimatedAreaChart例子,我修改了它,以基于LineGraph为您制作一个类似的例子。 请看一下这个例子,希望它满足您的需求!

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;


public class AnimatedLineChart extends Application {

    private static final int MAX_DATA_POINTS = 50;
    private int xSeriesData = 0;
    private XYChart.Series<Number, Number> series1 = new XYChart.Series<>();
    private XYChart.Series<Number, Number> series2 = new XYChart.Series<>();
    private XYChart.Series<Number, Number> series3 = new XYChart.Series<>();
    private ExecutorService executor;
    private ConcurrentLinkedQueue<Number> dataQ1 = new ConcurrentLinkedQueue<>();
    private ConcurrentLinkedQueue<Number> dataQ2 = new ConcurrentLinkedQueue<>();
    private ConcurrentLinkedQueue<Number> dataQ3 = new ConcurrentLinkedQueue<>();

    private NumberAxis xAxis;

    private void init(Stage primaryStage) {

        xAxis = new NumberAxis(0, MAX_DATA_POINTS, MAX_DATA_POINTS / 10);
        xAxis.setForceZeroInRange(false);
        xAxis.setAutoRanging(false);
        xAxis.setTickLabelsVisible(false);
        xAxis.setTickMarkVisible(false);
        xAxis.setMinorTickVisible(false);

        NumberAxis yAxis = new NumberAxis();

        // Create a LineChart
        final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis) {
            // Override to remove symbols on each data point
            @Override
            protected void dataItemAdded(Series<Number, Number> series, int itemIndex, Data<Number, Number> item) {
            }
        };

        lineChart.setAnimated(false);
        lineChart.setTitle("Animated Line Chart");
        lineChart.setHorizontalGridLinesVisible(true);

        // Set Name for Series
        series1.setName("Series 1");
        series2.setName("Series 2");
        series3.setName("Series 3");

        // Add Chart Series
        lineChart.getData().addAll(series1, series2, series3);

        primaryStage.setScene(new Scene(lineChart));
    }


    @Override
    public void start(Stage stage) {
        stage.setTitle("Animated Line Chart Sample");
        init(stage);
        stage.show();


        executor = Executors.newCachedThreadPool(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(true);
                return thread;
            }
        });

        AddToQueue addToQueue = new AddToQueue();
        executor.execute(addToQueue);
        //-- Prepare Timeline
        prepareTimeline();
    }

    private class AddToQueue implements Runnable {
        public void run() {
            try {
                // add a item of random data to queue
                dataQ1.add(Math.random());
                dataQ2.add(Math.random());
                dataQ3.add(Math.random());

                Thread.sleep(500);
                executor.execute(this);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    //-- Timeline gets called in the JavaFX Main thread
    private void prepareTimeline() {
        // Every frame to take any data from queue and add to chart
        new AnimationTimer() {
            @Override
            public void handle(long now) {
                addDataToSeries();
            }
        }.start();
    }

    private void addDataToSeries() {
        for (int i = 0; i < 20; i++) { //-- add 20 numbers to the plot+
            if (dataQ1.isEmpty()) break;
            series1.getData().add(new XYChart.Data<>(xSeriesData++, dataQ1.remove()));
            series2.getData().add(new XYChart.Data<>(xSeriesData++, dataQ2.remove()));
            series3.getData().add(new XYChart.Data<>(xSeriesData++, dataQ3.remove()));
        }
        // remove points to keep us at no more than MAX_DATA_POINTS
        if (series1.getData().size() > MAX_DATA_POINTS) {
            series1.getData().remove(0, series1.getData().size() - MAX_DATA_POINTS);
        }
        if (series2.getData().size() > MAX_DATA_POINTS) {
            series2.getData().remove(0, series2.getData().size() - MAX_DATA_POINTS);
        }
        if (series3.getData().size() > MAX_DATA_POINTS) {
            series3.getData().remove(0, series3.getData().size() - MAX_DATA_POINTS);
        }
        // update
        xAxis.setLowerBound(xSeriesData - MAX_DATA_POINTS);
        xAxis.setUpperBound(xSeriesData - 1);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

NB我没有照顾更新X轴上的值,你可以这样做!


Based on JewelSea's example on AnimatedAreaChart, I modified it to make a similar example for you based on LineGraph. Please have a look at the example, hope it satisfies your need!

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;


public class AnimatedLineChart extends Application {

    private static final int MAX_DATA_POINTS = 50;
    private int xSeriesData = 0;
    private XYChart.Series<Number, Number> series1 = new XYChart.Series<>();
    private XYChart.Series<Number, Number> series2 = new XYChart.Series<>();
    private XYChart.Series<Number, Number> series3 = new XYChart.Series<>();
    private ExecutorService executor;
    private ConcurrentLinkedQueue<Number> dataQ1 = new ConcurrentLinkedQueue<>();
    private ConcurrentLinkedQueue<Number> dataQ2 = new ConcurrentLinkedQueue<>();
    private ConcurrentLinkedQueue<Number> dataQ3 = new ConcurrentLinkedQueue<>();

    private NumberAxis xAxis;

    private void init(Stage primaryStage) {

        xAxis = new NumberAxis(0, MAX_DATA_POINTS, MAX_DATA_POINTS / 10);
        xAxis.setForceZeroInRange(false);
        xAxis.setAutoRanging(false);
        xAxis.setTickLabelsVisible(false);
        xAxis.setTickMarkVisible(false);
        xAxis.setMinorTickVisible(false);

        NumberAxis yAxis = new NumberAxis();

        // Create a LineChart
        final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis) {
            // Override to remove symbols on each data point
            @Override
            protected void dataItemAdded(Series<Number, Number> series, int itemIndex, Data<Number, Number> item) {
            }
        };

        lineChart.setAnimated(false);
        lineChart.setTitle("Animated Line Chart");
        lineChart.setHorizontalGridLinesVisible(true);

        // Set Name for Series
        series1.setName("Series 1");
        series2.setName("Series 2");
        series3.setName("Series 3");

        // Add Chart Series
        lineChart.getData().addAll(series1, series2, series3);

        primaryStage.setScene(new Scene(lineChart));
    }


    @Override
    public void start(Stage stage) {
        stage.setTitle("Animated Line Chart Sample");
        init(stage);
        stage.show();


        executor = Executors.newCachedThreadPool(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(true);
                return thread;
            }
        });

        AddToQueue addToQueue = new AddToQueue();
        executor.execute(addToQueue);
        //-- Prepare Timeline
        prepareTimeline();
    }

    private class AddToQueue implements Runnable {
        public void run() {
            try {
                // add a item of random data to queue
                dataQ1.add(Math.random());
                dataQ2.add(Math.random());
                dataQ3.add(Math.random());

                Thread.sleep(500);
                executor.execute(this);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    //-- Timeline gets called in the JavaFX Main thread
    private void prepareTimeline() {
        // Every frame to take any data from queue and add to chart
        new AnimationTimer() {
            @Override
            public void handle(long now) {
                addDataToSeries();
            }
        }.start();
    }

    private void addDataToSeries() {
        for (int i = 0; i < 20; i++) { //-- add 20 numbers to the plot+
            if (dataQ1.isEmpty()) break;
            series1.getData().add(new XYChart.Data<>(xSeriesData++, dataQ1.remove()));
            series2.getData().add(new XYChart.Data<>(xSeriesData++, dataQ2.remove()));
            series3.getData().add(new XYChart.Data<>(xSeriesData++, dataQ3.remove()));
        }
        // remove points to keep us at no more than MAX_DATA_POINTS
        if (series1.getData().size() > MAX_DATA_POINTS) {
            series1.getData().remove(0, series1.getData().size() - MAX_DATA_POINTS);
        }
        if (series2.getData().size() > MAX_DATA_POINTS) {
            series2.getData().remove(0, series2.getData().size() - MAX_DATA_POINTS);
        }
        if (series3.getData().size() > MAX_DATA_POINTS) {
            series3.getData().remove(0, series3.getData().size() - MAX_DATA_POINTS);
        }
        // update
        xAxis.setLowerBound(xSeriesData - MAX_DATA_POINTS);
        xAxis.setUpperBound(xSeriesData - 1);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

N.B. I haven't taken care of updating the values on the X-axis, you can do that !

相关问答

更多
  • UNTESTED Sub Update_Slope() ActiveSheet.ChartObjects("Chart(2)").Activate ActiveChart.Axes(xlCategory).MinimumScale = Range("F68").Value ActiveChart.Axes(xlCategory).MaximumScale = Range("F58").Value ActiveSheet.ChartObjects("Chart(4)").Ac ...
  • 据我所知,所有用于建立PieChart ,如PieChart.Data ,当然还有ObservableList都已经设计好,以便在更改内容时更新PieChart ,无论是列表本身还是内部值Data对象。 请参阅绑定章节,了解如何完成此操作。 但是你不需要为PieChart编写自己的绑定。 下面的代码应该做你想要的。 使用addData(String name, double value)为饼图创建新的Data对象,或者更新与方法的第一个参数具有相同name的现有Data对象。 当对列表进行更改(添加新Dat ...
  • 基于JewelSea在AnimatedAreaChart上的例子,我修改了它,以基于LineGraph为您制作一个类似的例子。 请看一下这个例子,希望它满足您的需求! import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.chart.LineChart; import javafx.scene.chart.Num ...
  • 你需要改变你的功能: function addData(label, xp1, yp1, xp2, yp2) { chart.data.labels.push(label); chart.data.datasets.push({ label: label, fill: false, data: [{ {x: xp1, y: yp1}, {x: xp2, y: yp2} }] }); chart.update(); } You need to change your function ...
  • 您需要的代码实际上比您拥有的代码简单得多。 您只需要创建一次图表对象,也不需要调用nv.addGraph() 。 我在这里更新了jsfiddle; 相关代码也在下面。 var chart = nv.models.lineChart(); chart.xAxis .axisLabel('Time (ms)') .tickFormat(d3.format(',r')); chart.yAxis .axisLabel('Voltage (v)') .tickFormat(d3.format(' ...
  • 而是使用您的图表作为DataProvider,您可以创建单独的LegendItems edit2:试试这个
    您没有向我们展示您的完整代码,但从您的描述中可以看出您可能选择了错误的路径。 解决此问题的一种方法是为您想要的路径指定一个特殊类,并相应地进行选择。 chartContainer.append("path") .attr("class", "chart"); chartContainer.select("path.chart"); 另一个问题是你不能真正使用.data()来更新绑定到DOM元素的数据,就像你正在使用它一样。 请改用.datum() 。 chartContainer.select( ...
  • 是的,有一种方法可以简单地更新基础chart.js图表数据,而无需每次都重新实例化图表。 您只需要使用API中的update(duration, lazy)函数。 这是我在我的一个应用程序中使用的示例(根据您的具体情况进行了修改)。 注意, chart是我的chart.js对象( new Chart()...返回的内容new Chart()... : assembledData = {}; assembledData.data = // data from api call in an acceptable ...
  • 问题是一个非常小的错字。 在JSON中, row应该是rows 。 例如,将示例JSON更改为 var result = { "cols":[ {"type":"string"}, {"type":"number"}], "rows":[ {"c":[{"v":"20-01-13"}, {"v":22}]}, {"c":[{"v":"21-01-13"}, {"v":24}]}, {"c":[{"v":"22-01-13"}, {"v":27}]} ]}; 和你的代码工作: 更新 查看构造函数的JavaS ...
  • 您可以在循环中使用addPoint来通过JSON中的所有数据点。 将所有点重新添加后,将redraw参数设置为false并重新绘制图表: load: function() { var chart = this; setInterval(function() { chart.series.forEach(function(s) { for (var i = 0; i < 20; i++) { s.addPoint(Math.random(), ...

相关文章

更多

最新问答

更多
  • 如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)
  • linux的常用命令干什么用的
  • 由于有四个新控制器,Auth刀片是否有任何变化?(Are there any changes in Auth blades due to four new controllers?)
  • 如何交换返回集中的行?(How to swap rows in a return set?)
  • 在ios 7中的UITableView部分周围绘制边界线(draw borderline around UITableView section in ios 7)
  • 使用Boost.Spirit Qi和Lex时的空白队长(Whitespace skipper when using Boost.Spirit Qi and Lex)
  • Java中的不可变类(Immutable class in Java)
  • WordPress发布查询(WordPress post query)
  • 如何在关系数据库中存储与IPv6兼容的地址(How to store IPv6-compatible address in a relational database)
  • 是否可以检查对象值的条件并返回密钥?(Is it possible to check the condition of a value of an object and JUST return the key?)
  • GEP分段错误LLVM C ++ API(GEP segmentation fault LLVM C++ API)
  • 绑定属性设置器未被调用(Bound Property Setter not getting Called)
  • linux ubuntu14.04版没有那个文件或目录
  • 如何使用JSF EL表达式在param中迭代变量(How to iterate over variable in param using JSF EL expression)
  • 是否有可能在WPF中的一个单独的进程中隔离一些控件?(Is it possible to isolate some controls in a separate process in WPF?)
  • 使用Python 2.7的MSI安装的默认安装目录是什么?(What is the default installation directory with an MSI install of Python 2.7?)
  • 寻求多次出现的表达式(Seeking for more than one occurrence of an expression)
  • ckeditor config.protectedSource不适用于editor.insertHtml上的html元素属性(ckeditor config.protectedSource dont work for html element attributes on editor.insertHtml)
  • linux只知道文件名,不知道在哪个目录,怎么找到文件所在目录
  • Actionscript:检查字符串是否包含域或子域(Actionscript: check if string contains domain or subdomain)
  • 将CouchDB与AJAX一起使用是否安全?(Is it safe to use CouchDB with AJAX?)
  • 懒惰地初始化AutoMapper(Lazily initializing AutoMapper)
  • 使用hasclass为多个div与一个按钮问题(using hasclass for multiple divs with one button Problems)
  • Windows Phone 7:检查资源是否存在(Windows Phone 7: Check If Resource Exists)
  • 无法在新线程中从FREContext调用getActivity()?(Can't call getActivity() from FREContext in a new thread?)
  • 在Alpine上升级到postgres96(/ usr / bin / pg_dump:没有这样的文件或目录)(Upgrade to postgres96 on Alpine (/usr/bin/pg_dump: No such file or directory))
  • 如何按部门显示报告(How to display a report by Department wise)
  • Facebook墙贴在需要访问令牌密钥后无法正常工作(Facebook wall post not working after access token key required)
  • Javascript - 如何在不擦除输入的情况下更改标签的innerText(Javascript - how to change innerText of label while not wiping out the input)
  • WooCommerce / WordPress - 不显示具有特定标题的产品(WooCommerce/WordPress - Products with specific titles are not displayed)